I have the following lines of bash script to test whether a file exists:
MYAPPPATH=$(find $APPDIR -iname myapp* -print)
if [ -e $MYAPPPATH ]
then
echo "File exists"
fi
However when file starting with "myapp" does not exist, therefore MYAPPPATH='', the above check succeeds again.
See what happens when using set -x
and the file does not exist:
++ find /path/to/app -iname 'myapp*' -print
+ MYAPPPATH=
+ '[' -e ']'
+ echo 'File exists'
What is the reason for this?
What do I need to do in order to make this work as expected?
Best Answer
When your variable is empty, your command becomes:
In this case, you call
[..]
with one argument-e
. String"-e"
is not null, sotest
return true.This behavior is defined by POSIX test:
To make it works, you must double quote your variable:
This works because
-e
with an argument that is an empty string is false.