Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 为什么空字符串上的[-n$var]为真?_Linux_Bash - Fatal编程技术网

Linux 为什么空字符串上的[-n$var]为真?

Linux 为什么空字符串上的[-n$var]为真?,linux,bash,Linux,Bash,代码: 输出: #!/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 ech

代码:

输出:

#!/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
manbash

-z字串

如果字符串的长度为零,则为True

-n字符串

如果字符串长度非零,则为True


有人能给我解释一下-n的这种行为吗?为什么它与-z不一致?谢谢

在BASH中引用变量或更好地使用
[…]

0
It exists!
It is empty.
它将打印:

if [[ -n $EXISTS ]]; then echo "It exists!"; else echo "It is empty."; fi
同样地:

It is empty.
[…]
的行为取决于关闭
]
之前的参数数量

如果只有一个参数,它将测试该参数是否为非空。由于字符串
“-n”
为非空,
[-n]
为真
-n
仅当后跟另一个参数时才被解释为运算符

要解决此问题,请引用参数,以便将其解释为单个空参数,而不是无参数:

EXISTS=""
if [ -n $EXISTS ]; then
    ...
fi

所以我才意识到这更多的是关于方括号的——这和双方括号的预期效果一样。两者兼而有之。请看答案和我的评论。@EtanReisner您的评论非常有用。谢谢忽略
[
并始终使用
test
(或者更好的做法是,在可用的情况下使用
[…]]
,并且POSIX兼容性不是问题)。您不太可能对
test
的参数的处理方式感到惊讶(因为它实际上看起来像一个命令),您不需要荒谬的最后一个
]
参数,它的唯一目的是进一步强化
[
是某种语法的错觉。我们不是告诉过您在这个主题的最后一个问题上使用引号吗?具体来说,这是因为当
$EXISTS
被取消引号,shell在
[-n$EXISTS]中展开变量时
它变成了
[-n]
,被
[
/
test
解释为
[-n-n]
(参见手册页),而
[[
没有空变量问题,引号使它看到
[-n']
EXISTS=""
if [ -n $EXISTS ]; then
    ...
fi
if [ -n "$EXISTS" ]; then
    ...
fi