Bash File Test – File Existence Test Always True

bashquotingshellshell-scripttest

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:

[ -e ]

In this case, you call [..] with one argument -e. String "-e" is not null, so test return true.

This behavior is defined by POSIX test:

In the following list, $1, $2, $3, and $4 represent the arguments presented to test:

0 arguments:

Exit false (1).

1 argument:

Exit true (0) if $1 is not null; otherwise, exit false.

....

To make it works, you must double quote your variable:

[ -e "$MYAPPPATH" ]

This works because -e with an argument that is an empty string is false.

Related Question