Bash confusing results for different file tests (test -f)

I am confused in bash by this expression:

$ var="" # empty var $ test -f $var; echo $? # test if such file exists 0 # and this file exists, amazing! $ test -f ""; echo $? # let try doing it without var 1 # and all ok 

I can not understand this behavior of bash, maybe someone can explain?

+4
source share
2 answers

This is because the empty $var extension is removed before test sees it. In fact, you run test -f and therefore there is only one arg test argument, namely -f . According to POSIX, one argument of type -f is true because it is not empty.

From the POSIX test specification (1) :

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

A file with an empty file name is never tested. Now with explicit test -f "" there are two arguments, and -f recognized as the operator for "checking the existence of the path argument".

+6
source

When var empty, $var will behave differently if quoted or not.

 test -f $var # <=> test -f ==> $? is 0 test -f "$var" # <=> test -f "" ==> $? is 1 

So this example tells us: we must quote $var .

+3
source

All Articles