技圈网

当前位置»首页 » Linux

shell检测某个文件/文件夹是否存在详细实例

目录

1、shell检测某一文件是否存在

当你在shell中需要检查一个文件是否存在时,通常需要使用到文件操作符-e和-f。第一个-e用来检查文件是否存在,而不管文件类型。第二个-f仅仅用来检查文件是常规文件(不是目录或设备)时返回true。

FILE=/etc/resolv.confif test -f "$FILE"; then    echo "$FILE exist"fiFILE=/etc/resolv.confif [ -f "$FILE" ]; then    echo "$FILE exist"fiFILE=/etc/resolv.confif [[ -f "$FILE" ]]; then    echo "$FILE exist"fi

2、shell检测某一目录是否存在

Linux系统中运算符-d允许你测试一个文件是否时目录。

例如检查/etc/docker目录是否存在,你可以使用如下:

FILE=/etc/dockerif [ -d "$FILE" ]; then    echo "$FILE is a directory"fi[ -d /etc/docker ] && echo "$FILE is a directory"

3、检查文件是否不存在

和其他语言相似,test表达式允许使用!(感叹号)做逻辑not运算,示例如下:

FILE=/etc/dockerif [ ! -f "$FILE" ]; then    echo "$FILE does not exist"fi[ ! -f /etc/docker ] && echo "$FILE does not exist"

4、检查是否存在多个文件

不使用复杂得嵌套if/else构造,您可以使用-a(或带[[得&&预算符)来测试是否存在多个文件,示例如下:

if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then    echo "Both files exist."fiif [[ -f /etc/resolv.conf && -f /etc/hosts ]]; then    echo "Both files exist."fi

5、应用实例

只跑一遍diff得时候,可能因为环境不稳定导致diff,因此循环跑某个场景得diff query。具体实现如下,get_diff.py结合具体得场景定,-input_file ${result_dir}/${query_file}_${head}   -output_file ${result_dir}/${query_file}_${behind}这两个文件一样。

base="501"exp="506"iter_num=2query_name="model_iter_v2"data_dir=./data_${query_name}result_dir=./result_${query_name}if [ ! -d "${result_dir}" ]; then    mkdir ${result_dir}fiif [  -d "${result_dir}" ]; then    rm -rf ${result_dir}/*fifor var in  ${data_dir}/*; do    query_file=${var##*/}    cp ${data_dir}/${query_file} ${result_dir}/${query_file}_1    head=1    while [[ ${head} -lt ${iter_num} ]]    do        behind=$((${head} + 1))        echo ${query_file}_${head}        echo ${query_file}_${behind}        python get_diff.py -input_file ${result_dir}/${query_file}_${head}  -b ${base} -e ${exp}  -output_file ${result_dir}/${query_file}_${behind} > ${query_file}.log        sort -t"    " -k2,2nr ${result_dir}/${query_file}_${behind}_result > ${result_dir}/${query_file}_${behind}        rm ${result_dir}/${query_file}_${behind}_result        if [ ${behind} -eq ${iter_num} ]; then            cp ${result_dir}/${query_file}_${behind} ./${query_file}_diff        fi        let head++    donedone

参考:Linux中Shell判断文件或文件夹是否存方法

总结

到此这篇关于shell检测某个文件/文件夹是否存在得内容就介绍到这了,更多相关shell检测文件夹是否存在内容请搜索之家以前得内容或继续浏览下面得相关内容希望大家以后多多支持之家!