Bash Shell运算符非零(-n)和零长度(-z)对于同一变量都返回True!!!难以想象的
为什么非零运算符和零运算符在shell脚本中都返回true?这毫无意义。 请看下面我写的小脚本。我将变量“零”设置为零。如果我将“零”设置为“”或Bash Shell运算符非零(-n)和零长度(-z)对于同一变量都返回True!!!难以想象的,bash,sh,Bash,Sh,为什么非零运算符和零运算符在shell脚本中都返回true?这毫无意义。 请看下面我写的小脚本。我将变量“零”设置为零。如果我将“零”设置为“”或zero=”“,也会得到相同的结果 谢谢你阅读这篇文章。请取笑我,直到我失去所有的现实感 与测试括号内的比较运算符一起使用时,引用变量 由于字符串拆分,最好的做法是在变量包含空格的情况下引用变量 在比较运算符的情况下,如果不使用,则会导致失败 n运算符的实际状态为“,-n测试要求在测试括号内引用字符串。” 下面是代码的更新版本,可以按预期工作: #!/
zero=”“
,也会得到相同的结果
谢谢你阅读这篇文章。请取笑我,直到我失去所有的现实感
与测试括号内的比较运算符一起使用时,引用变量
由于字符串拆分,最好的做法是在变量包含空格的情况下引用变量
在比较运算符的情况下,如果不使用,则会导致失败
n运算符的实际状态为“,-n测试要求在测试括号内引用字符串。”
下面是代码的更新版本,可以按预期工作:
#!/usr/bin/env bash
zero= # Zero-length ("null") string variable.
#the below code prints $zero is null.
echo "Test for zero length using -n comparison operator"
if [ -n "$zero" ] ; # if string is not null
then
echo "\$zero is not null" ;
else
echo "\$zero is null"
fi
echo "Test for zero length using -z comparison operator"
#the below code prints $zero is null.
if [ -z "$zero" ]
then
echo "\$zero is null."
else
echo "\$zero is NOT null."
fi
操作员参考
- -n比较运算符检查字符串是否为空
- z比较运算符的作用正好相反,如果字符串为null,即长度为零,则返回true
[…]
中引用您的变量,例如如果[-z“$zero”]
(您已收到警告…)您所做的是[-n]&&echo“true”
和[-z]&&echo“true”
如果您正在使用bash并且非常不愿意引用,您可以使用双大括号:[-n$zero]
和[-z$zero]]
。这将无法移植到其他shell。警告:双引号有时甚至在[[]]
内部也很重要,例如,[[[$var1=$var2]]
将var2
的内容视为全局(通配符)模式,而[[$var1=“$var2”]
将其视为文字字符串。在我看来,最好养成在shell中双引号引用变量引用的习惯,而不要试图跟踪何时关闭它们是安全的。用于查找shell代码中的问题。在这种情况下,它会警告缺少引号。
#!/usr/bin/env bash
zero= # Zero-length ("null") string variable.
#the below code prints $zero is null.
echo "Test for zero length using -n comparison operator"
if [ -n "$zero" ] ; # if string is not null
then
echo "\$zero is not null" ;
else
echo "\$zero is null"
fi
echo "Test for zero length using -z comparison operator"
#the below code prints $zero is null.
if [ -z "$zero" ]
then
echo "\$zero is null."
else
echo "\$zero is NOT null."
fi