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

后端 未结 2 575
误落风尘
误落风尘 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.

提交回复
热议问题