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

前端之家收集整理的这篇文章主要介绍了为什么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.f2er.com/bash/384357.html

猜你在找的Bash相关文章