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

标签 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
    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/

相关文章:

bash - Bash 模式替换变量扩展中的引号

bash - 如何从命令行重新加载 .bash_profile

bash - 在 bash 中为每个 "wildcard"参数添加一些文本

linux - 在启动和关闭时遇到运行 shell 脚本的错误

linux - MonoDevelop 不工作(安装了 xterm)

bash - 如何覆盖 .bash_aliases 中设置的别名

linux - 如何在特定行之后使用 sed 每隔一行打印一次

linux - Apache 虚拟主机无法在 Ubuntu 14.04 LTS 上运行

c - 如何用C语言打开、读取、写入串口?

linux - 您好,使用 NFS 挂载和共享服务器