Bash如果[-d $1]为空$1返回true

所以我有以下小脚本并不断疑惑..
#!/bin/bash

if [ -d $1 ]; then
  echo 'foo'
else
  echo 'bar'
fi

..为什么在没有参数的情况下打印foo?对于空字符串,test [-d]如何返回true?

来自: info coreutils 'test invocation'(通过人体测试找到参考):

If EXPRESSION is omitted,test' returns false. **If EXPRESSION is a
single argument,
test’ returns false if the argument is null and true
otherwise**. The argument can be any string,including strings like
-d',-1′,--',–help’,and --version' that most other programs
would treat as options. To get help and version information,invoke
the commands
[ –help’ and `[ –version’,without the usual closing
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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...