所以我有以下小脚本并不断疑惑..
#!/bin/bash if [ -d $1 ]; then echo 'foo' else echo 'bar' fi
..为什么在没有参数的情况下打印foo?对于空字符串,test [-d]如何返回true?
来自:
原文链接:https://www.f2er.com/bash/383306.htmlinfo coreutils 'test invocation'
(通过人体测试找到参考):
If EXPRESSION is omitted,
test' returns false. **If EXPRESSION is a
test’ returns false if the argument is null and true
single argument,
otherwise**. The argument can be any string,including strings like
-d',
-1′,--',
–help’,and--version' that most other programs
[ –help’ and `[ –version’,without the usual closing
would treat as options. To get help and version information,invoke
the commands
brackets.
正确突出显示:
If EXPRESSION is a single argument,`test’ returns false if the
argument is null and true otherwise
因此,每当我们做[something]时,如果某些东西不为null,它将返回true:
$[ -d ] && echo "yes" yes $[ -d "" ] && echo "yes" $ $[ -f ] && echo "yes" yes $[ t ] && echo "yes" yes
看到第二个[-d“”]&& echo“yes”返回false,你得到解决这个问题的方法:引用$1,以便-d总是得到一个参数:
if [ -d "$1" ]; then echo 'foo' else echo 'bar' fi