如果我想检查空字符串,我会这样做
[ -z $mystr ]
但是如果我想检查变量是否已经定义了怎么办?还是 Bash 脚本没有区别?
最佳答案
我认为 Vinko 暗示(如果未说明)您所寻求的答案的 answer ,尽管它没有简单地拼写出来。区分VAR是否已设置但为空或未设置,可以使用:
if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi
您可能可以将第二行的两个测试合并为一个:
if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi
但是,如果您阅读 Autoconf 的文档,您会发现他们不建议将术语与 '-a
' 结合使用,而是建议使用单独的简单测试与 &&
。我还没有遇到有问题的系统;这并不意味着它们过去不存在(但它们现在可能非常罕见,即使它们在遥远的过去并不那么罕见)。
您可以找到这些和其他相关的详细信息shell parameter expansions , test
or [
命令和 conditional expressions在 Bash 手册中。
我最近通过电子邮件询问了这个问题的答案:
You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion
if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
Wouldn't this accomplish the same?
if [ -z "${VAR}" ]; then echo "VAR is not set at all"; fi
公平的问题 - 答案是“不,你的更简单的替代方案不会做同样的事情”。
假设我在你的测试之前写了这个:
VAR=
您的测试会说“VAR 根本没有设置”,但我的测试会说(暗示因为它什么也没回显)“VAR 已设置但其值可能为空”。试试这个脚本:
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo "JL:1 VAR is not set at all"; fi
if [ -z "${VAR}" ]; then echo "MP:1 VAR is not set at all"; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo "JL:2 VAR is not set at all"; fi
if [ -z "${VAR}" ]; then echo "MP:2 VAR is not set at all"; fi
)
输出是:
JL:1 VAR is not set at all MP:1 VAR is not set at all MP:2 VAR is not set at all
In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value}
and ${VAR:=value}
notations make. Ditto for ${VAR-value}
and ${VAR:-value}
, and ${VAR+value}
and ${VAR:+value}
, and so on.
As Gili points out in his answer, if you run bash
with the set -o nounset
option, then the basic answer above fails with unbound variable
. It is easily remedied:
if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo "VAR is set but empty"; fi
或者您可以使用 set +u
取消 set -o nounset
选项(set -u
等同于 set - o 名词集
).
关于bash - 如何判断字符串是否未在 Bash shell 脚本中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/228544/