我在bash中被以下表达式弄糊涂了:
$ var="" # empty var
$ test -f $var; echo $? # test if such file exists
0 # and this file exists, amazing!
$ test -f ""; echo $? # let's try doing it without var
1 # and all ok
我不能理解这种殴打行为,也许有人能解释?
这是因为$var
的空扩展在test
看到它之前就被删除了。您实际上正在运行test -f
,因此test
只有一个arg,即-f
。根据POSIX,像-f
这样的单个arg是真的,因为它不是空的。
来自POSIX测试(1)规范:
1 argument:
Exit true (0) if `$1` is not null; otherwise, exit false.
从来没有对文件名为空的文件进行过测试。现在有了显式test -f ""
,就有了两个参数,-f
被识别为"测试路径参数的存在性"的运算符。
当var
为空时,无论是否引用,$var
的行为都会有所不同。
test -f $var # <=> test -f ==> $? is 0
test -f "$var" # <=> test -f "" ==> $? is 1
所以这个例子告诉我们:我们应该引用$var
。