这将检查文件是否存在:
#!/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
如何仅检查文件是否不存在?
当前回答
测试命令(此处写为[)有一个“not”逻辑运算符!(感叹号):
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
其他回答
如果要使用test而不是[],则可以使用!要获得否定:
if ! test "$FILE"; then
echo "does not exist"
fi
值得一提的是,如果需要执行单个命令,可以缩写
if [ ! -f "$file" ]; then
echo "$file"
fi
to
test -f "$file" || echo "$file"
or
[ -f "$file" ] || echo "$file"
要反转测试,请使用“!”。这相当于其他语言中的“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!"
[[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"
此外,该文件可能是一个断开的符号链接,或者是一个非常规文件,例如套接字、设备或fifo。例如,要添加断开符号链接的检查:
if [[ ! -f $FILE ]]; then
if [[ -L $FILE ]]; then
printf '%s is a broken symlink!\n' "$FILE"
else
printf '%s does not exist!\n' "$FILE"
fi
fi
envfile=.env
if [ ! -f "$envfile" ]
then
echo "$envfile does not exist"
exit 1
fi