当前位置:首页 » 《随便一记》 » 正文

shell检测某个文件/文件夹是否存在

27 人参与  2023年04月18日 09:39  分类 : 《随便一记》  评论

点击全文阅读


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脚本判断文件或文件夹是否存方法 | linux资讯


点击全文阅读


本文链接:http://zhangshiyu.com/post/59754.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1