代码:
#!/bin/bash
EXISTS=""
echo ${#EXISTS} #print size of string
if [ -n $EXISTS ]; then
echo "It exists!"
else
echo "It is empty."
fi
if [ -z $EXISTS ]; then
echo "It is empty."
else
echo "It exists!"
fi
输出:
0
It exists!
It is empty.
来自 man bash
:
-z string
True if the length of string is zero.
-n 字符串
True if the length of string is non-zero.
有人可以向我解释 -n 的这种行为,以及为什么它与 -z 不一致吗?谢谢!
最佳答案
在 BASH 中引用变量或更好地使用 [[...]]
:
if [[ -n $EXISTS ]]; then echo "It exists!"; else echo "It is empty."; fi
它将打印:
It is empty.
类似地:
if [ -n "$EXISTS" ]; then echo "It exists!"; else echo "It is empty."; fi
It is empty.
关于linux - 为什么 [ -n $var ] 在空字符串上为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922831/