Seán Hayes
Seán Hayes

Reputation: 4360

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.

Upvotes: 3

Views: 873

Answers (3)

ghostdog74
ghostdog74

Reputation: 342363

you can use test

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

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881403

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

Upvotes: 2

codaddict
codaddict

Reputation: 455020

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.

Upvotes: 1

Related Questions