这将检查文件是否存在:
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
如何仅检查文件是否不存在?
这将检查文件是否存在:
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
如何仅检查文件是否不存在?
当前回答
有时使用&&和|运算符可能很方便。
类似于(如果您有命令“test”):
test -b $FILE && echo File not there!
or
test -b $FILE || echo File there!
其他回答
您可以这样做:
[[ ! -f "$FILE" ]] && echo "File doesn't exist"
or
if [[ ! -f "$FILE" ]]; then
echo "File doesn't exist"
fi
如果要同时检查文件和文件夹,请使用-e选项而不是-f-对于常规文件、目录、套接字、字符特殊文件、块特殊文件等,e返回true。
测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
使用!:否定测试中的表达式([是其别名)
#!/bin/bash
FILE=$1
if [ ! -f "$FILE" ]
then
echo "File $FILE does not exist"
fi
相关的手册页是man-test,或者,对于内置的bash命令,相当于man[-或help-test或help]。
或者(不常用)您可以使用以下方法否定测试结果:
if ! [ -f "$FILE" ]
then
echo "File $FILE does not exist"
fi
该语法在“管道”和“复合命令”部分的“man 1 bash”中进行了描述。
此shell脚本还可用于查找目录中的文件:
echo "enter file"
read -r a
if [ -s /home/trainee02/"$a" ]
then
echo "yes. file is there."
else
echo "sorry. file is not there."
fi
您还可以在一行中对多个命令进行分组
[-f“文件名”]||(echo test1&&echo test2&&echo test3)
or
[-f“文件名”]| |{echo test1&&echo test2&&echo test3;}
如果文件名不退出,输出将为
test1
test2
test3
注意:(…)在子shell中运行,{…;}在同一个shell中运行。