Bash,不同文件测试的结果令人困惑(test -f) [英] Bash, confusing results for different file tests (test -f)

查看:75
本文介绍了Bash,不同文件测试的结果令人困惑(test -f)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash的这种表达感到困惑:

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's try doing it without var
1 # and all ok

我不明白这种bash行为,也许任何人都可以解释?

I can't understand such bash behaviour, maybe anybody can explain?

推荐答案

这是因为$var的空扩展名在test看到之前就被删除了.您实际上正在运行test -f,因此test只有一个arg,即-f.根据POSIX,像-f这样的单个arg是正确的,因为它不为空.

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.

来自 POSIX test(1)规范:

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

对于文件名称为空的文件,永远不会进行测试.现在,有了显式的test -f "",有两个参数,并且-f被识别为测试路径参数是否存在"的运算符.

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".

这篇关于Bash,不同文件测试的结果令人困惑(test -f)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆