这将检查文件是否存在:
#!/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
如何仅检查文件是否不存在?
当前回答
值得一提的是,如果需要执行单个命令,可以缩写
if [ ! -f "$file" ]; then
echo "$file"
fi
to
test -f "$file" || echo "$file"
or
[ -f "$file" ] || echo "$file"
其他回答
您还可以在一行中对多个命令进行分组
[-f“文件名”]||(echo test1&&echo test2&&echo test3)
or
[-f“文件名”]| |{echo test1&&echo test2&&echo test3;}
如果文件名不退出,输出将为
test1
test2
test3
注意:(…)在子shell中运行,{…;}在同一个shell中运行。
要反转测试,请使用“!”。这相当于其他语言中的“not”逻辑运算符。试试看:
if [ ! -f /tmp/foo.txt ];
then
echo "File not found!"
fi
或以稍微不同的方式书写:
if [ ! -f /tmp/foo.txt ]
then echo "File not found!"
fi
或者您可以使用:
if ! [ -f /tmp/foo.txt ]
then echo "File not found!"
fi
或者,将所有内容放在一起:
if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi
可以写成(使用“and”运算符:&&):
[ ! -f /tmp/foo.txt ] && echo "File not found!"
看起来像这样更短:
[ -f /tmp/foo.txt ] || echo "File not found!"
最简单的方法
FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"
envfile=.env
if [ ! -f "$envfile" ]
then
echo "$envfile does not exist"
exit 1
fi
如果要使用test而不是[],则可以使用!要获得否定:
if ! test "$FILE"; then
echo "does not exist"
fi