[SGVLUG] bash scripting - checking for file existence

Rae Yip rae.yip at gmail.com
Sat Sep 11 16:15:12 PDT 2010


I'm not sure what question was being asked, but you should always
double-quote variables inside test brackets:

if [ -e "$FILE" ]; then
    futz_with "$FILE"
fi

The quotes ensure that the argument count is invariant; remember the
shell is responsible for tokenizing and passing arguments to commands,
so unquoted null strings are never even seen by '[' or 'test'.

The reason why test returns true whenever it is passed a single
non-null argument is because of this legacy usage:

if [ "$FLAG" ]; then
    do_something
fi

And you should always have a space before the trailing ]. Otherwise
'[' declares a syntax error and the test evaluates as false. But note
that [ -e ''] and [ -e ""] are the same as [ -e ] after substitution,
so it doesn't fail.

-Rae.


More information about the SGVLUG mailing list