与bash不是运算符的奇怪

时间:2010-09-28 04:45:49

标签: bash file exists

我正在尝试确定文件或目录是否不存在。我尝试了以下命令来查看文件是否存在并且它们是否正常工作:

if [ -a 'settings.py' ]; then echo 'exists'; fi
exists #output
if [ -a 'foo' ]; then echo 'exists'; fi #outputs nothing

但是当我尝试这个时:

if [ ! -a 'settings.py' ]; then echo 'does not exist'; fi
does not exist #shouldn't be output since the file does exist
if [ ! -a 'foo' ]; then echo 'does not exist'; fi
does not exist
无论如何都输出

'不存在'。

3 个答案:

答案 0 :(得分:2)

之前我遇到过[命令的问题。我更喜欢[[变体,因为它更强大,而且根据我的经验,它更不容易出现这样的“陷阱”。

如果使用[[命令,则测试命令可以正常工作:

pax> touch qq
pax> if [[ -a qq ]] ; then echo exists ; fi
exists
pax> if [[ ! -a qq ]] ; then echo not exists ; fi
pax> rm qq
pax> if [[ ! -a qq ]] ; then echo not exists ; fi
not exists

答案 1 :(得分:1)

尝试使用-e代替-a

Linux Documentation Project上的此页面说明了:

-a-e的效果完全相同。但它已被弃用,不鼓励使用它。

答案 2 :(得分:0)

您可以使用test

test -e "$file" && echo "exists"