开发者

Strangeness with bash not operator

I'm trying to determine if a file or directory doesn't exist. I tried the following commands to see if a file does exist and they work correctly:

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

But when I try this:

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

'does not exist' is output no matter what开发者_JAVA百科.


I've had problems with the [ command before. I prefer the [[ variant since it's much more powerful and, in my experience, less prone to "gotchas" like this.

If you use the [[ command, your test commands work fine:

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


Try using -e in place of -a

This page on the Linux Documentation Project says:

-a is identical in effect to -e. But it has been deprecated, and its use is discouraged.


you can use test

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜