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

后端 未结 2 574
误落风尘
误落风尘 2021-01-18 17:15

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         


        
相关标签:
2条回答
  • 2021-01-18 17:54

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

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

    So this example tells us: we should quote the $var.

    0 讨论(0)
  • 2021-01-18 17:59

    It's because the empty expansion of $var is removed before test sees it. You are actually running test -f and thus there's only one arg to test, namely -f. According to POSIX, a single arg like -f is true because it is not empty.

    From POSIX test(1) specification:

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

    There's never a test for a file with an empty file name. Now with an explicit test -f "" there are two args and -f is recognized as the operator for "test existence of path argument".

    0 讨论(0)
提交回复
热议问题