Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strangeness with bash not operator

Tags:

file

bash

exists

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.

like image 829
Seán Hayes Avatar asked Aug 29 '26 03:08

Seán Hayes


2 Answers

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
like image 52
paxdiablo Avatar answered Aug 30 '26 19:08

paxdiablo


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.

like image 25
codaddict Avatar answered Aug 30 '26 20:08

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!