我使用以下脚本来查看文件是否存在:
#!/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 [ $FILE does not exist ]; then
echo "File $FILE does not exist."
fi
该测试命令([
在这里)有一个“非”逻辑运算符是感叹号(类似于许多其他语言)。试试这个:
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
更简洁地说:[!-f /tmp/foo.txt] &&回显“找不到文件!”
我为“如果2个文件中的任何一个不存在”找到正确的语法有点费劲。以下两种工作:
if [ ! \( -f "f1" -a -f "f2" \) ] ; then echo MISSING; fi
if [ ! -f "f1" ] || [ ! -f "f2" ] ; then echo MISSING; fi
@DavidWinterbottom更加鲜活:
[ -f /tmp/foo.txt ] || echo "File not found!"
参数可以是以下任意一项:
-e: Returns true value, if file exists
-f: Return true value, if file exists and regular file
-r: Return true value, if file exists and is readable
-w: Return true value, if file exists and is writable
-x: Return true value, if file exists and is executable
-d: Return true value, if exists and is a directory
! -f
与with搭配&&
使用-f
与with搭配使用存在不对称性||
。这与不存在/存在检查返回的退出代码有关。如果您希望您的行始终以退出代码0干净地退出(有时您不希望此约束),则这两种方法不可互换。另外,只需使用一条if
语句,您就不必担心不存在/存在检查的退出代码。