【问题标题】:Why testing for non-empty string using -n always true? [duplicate]为什么使用 -n 测试非空字符串总是正确的? [复制]
【发布时间】:2020-09-24 11:03:23
【问题描述】:

你好,我有一个简单的例子让我很困惑:

#!bin/bash
#test_str is a script to test whether a string is empty or not

x=''
if [ -n $x ]
then  
    echo "'$x' is not empty"
else 
    echo "'$x' empty"
fi

chmod u+x test_str
./test_str

输出:

'' is not empty
  • 如果我没有声明变量(此处为 x),也会发生这种情况。

  • 如果我使用标志 -z 来测试是否为空,它可以正常工作:

      if [ -z $x ]
      then  
          echo "'$x' is  empty"
      else 
          echo "'$x' not empty"
      fi
    

输出:

'' is empty
  • 那么如何正确使用-n呢? 谢谢!

【问题讨论】:

  • 引用它! [ -n "$x" ] 没有它,构造被评估为[ -n ] 这是总是 true
  • 重复的可能是stackoverflow.com/questions/6852612/… 搜索-n 时很难找到重复的:/
  • @Inian:请您解释一下。还是将其添加为答案?
  • @Inian:很好用,谢谢。最后一个问题:我是否也应该使用"" 作为标志-z?如果不是,为什么?
  • 如有疑问,请务必查阅手册 - gnu.org/software/bash/manual/html_node/…。搜索 -z string-n string

标签: string bash shell


【解决方案1】:

这是因为[ -n $n ] 扩展为[ -n ],所以没有什么可比较的,它将返回true

相反,您应该使用[ -n "${n}" ] 来防止此类错误并且 来防止通配符。

【讨论】:

  • 旁注:如果 glob 字符在 $n 的值中,则没有通配符。
  • 这个[ -z $n ]是怎么解释的?
  • -z 确实检查了变量的 existenze,而不是值。但你也应该改用[ -z "$n" ]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-25
  • 2020-09-23
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多