加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:33:12 所属栏目:安全 来源:网络整理
导读:所以我有以下小脚本并不断疑惑.. #!/bin/bashif [ -d $1 ]; then echo 'foo'else echo 'bar'fi ..为什么在没有参数的情况下打印foo?对于空字符串,test [-d]如何返回true? 来自: info coreutils 'test invocation' (通过人体测试找到参考): If EXPRESSION
所以我有以下小脚本并不断疑惑..
#!/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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读