Bash中的-z是什么意思?

535

I'm looking at the following code:

if [ -z $2 ]; then
        echo "usage: ...

这里的三个点并不是重要的细节。
或许是我的搜索方式有误,但我找不到关于-z选项的解释。


1
https://dev59.com/slnUa4cB1Zd3GeqPXydp - devnull
1
https://dev59.com/R3VC5IYBdhLWcg3woSxW - devnull
4个回答

705

2
我找到了另一个优秀且详细的解释 - https://dev59.com/UHA65IYBdhLWcg3w1SfU - valentt
113
另外,-n-z 的相反。当字符串不为 null 且不为空时,if [ -n "${1}" ] 条件成立。 - Ryan
16
“-n”选项是否与“if [ $2 ]”的默认行为重复,或者它们之间存在一些区别? - bbarker

75
-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

39

35

-z string表示如果string的长度为,则条件成立。


3
如果它是字符串undefined(如果这是一件事)或者是一个数字,该怎么办? - Peter Mortensen
1
@PeterMortensen 如果你使用 if [[ -z "${YOUR_ENV_VAR}" ]],当该环境变量为空时,它将在运行时插值为 if [[ -z "" ]],从而导致逻辑上的真,这正是你想要的。 - peterrus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接