tags:

views:

31

answers:

3

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.

+1  A: 

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.

codaddict
Zack
A: 

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
paxdiablo
I couldn't disagree more -- `[` is portable, if you know all its quirks; `[[` cannot be relied upon to exist.
Zack
@Zack, the question is tagged `bash`. I'm aware that other shells may not provide it. And I'm sure you could disagree more - you just have to try harder :-)
paxdiablo
Dennis Williamson
I don't believe in writing bash-specific shell scripts; if you need something that portable shell doesn't have it's time to break out a real scripting language...
Zack
A: 

you can use test

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