微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么bash -n和-z测试运算符不能反转$@

function wtf() {
  echo "\$*='$*'"
  echo "\$@='$@'"
  echo "\$@='"$@"'"
  echo "\$@='""$@""'"
  if [ -n "$*" ]; then echo " [ -n \$* ]"; else echo "![ -n \$* ]"; fi
  if [ -z "$*" ]; then echo " [ -z \$* ]"; else echo "![ -z \$* ]"; fi
  if [ -n "$@" ]; then echo " [ -n \$@ ]"; else echo "![ -n \$@ ]"; fi
  if [ -z "$@" ]; then echo " [ -z \$@ ]"; else echo "![ -z \$@ ]"; fi
}

wtf

产生

06001

虽然在我看来[-n $@]应该是假的,因为7.3 Other Comparison Operators表示[-n“$X”]应该是所有$X的[-z“$X”]的倒数.

-z

string is null,that is,has zero length

06002

-n

string is not null.

The -n test requires that the string be quoted within the test brackets. Using an unquoted string with ! -z,or even just the unquoted string alone within test brackets (see Example 7-6) normally works,however,this is an unsafe practice. Always quote a tested string. [1]

我知道$@是特殊的,但我不知道它是否足以违反布尔否定.这里发生了什么?

$bash -version | head -1
GNU bash,version 4.2.42(2)-release (i386-apple-darwin12.2.0)

实际的数字退出代码均为1或0

$[ -n "$@" ]; echo "$?"
0
当$@为空时,“$@”不会扩展为空字符串;它完全被删除了.所以你的测试不是
[ -n "" ]

反而

[ -n ]

现在-n不是一个运算符,而只是一个非空字符串,它总是测试为true.

原文地址:https://www.jb51.cc/bash/384357.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐