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

Grizelda ·
更新时间:2024-05-15
· 1618 次阅读

目录

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

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

3、检查文件是否不存在

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

5、应用实例

总结

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

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

FILE=/etc/resolv.conf if test -f "$FILE"; then echo "$FILE exist" fi FILE=/etc/resolv.conf if [ -f "$FILE" ]; then echo "$FILE exist" fi FILE=/etc/resolv.conf if [[ -f "$FILE" ]]; then echo "$FILE exist" fi 2、shell检测某一目录是否存在

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

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

FILE=/etc/docker if [ -d "$FILE" ]; then echo "$FILE is a directory" fi [ -d /etc/docker ] && echo "$FILE is a directory" 3、检查文件是否不存在

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

FILE=/etc/docker if [ ! -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." fi if [[ -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=2 query_name="model_iter_v2" data_dir=./data_${query_name} result_dir=./result_${query_name} if [ ! -d "${result_dir}" ]; then mkdir ${result_dir} fi if [ -d "${result_dir}" ]; then rm -rf ${result_dir}/* fi for 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++ done done

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

总结

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



shell

需要 登录 后方可回复, 如果你还没有账号请 注册新账号