Bash,不同文件测试(test-f)的结果令人困惑



我在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

最新更新