"test -v $ TESTENV"即使定义了TESTENV,也始终为假 [英] "test -v $TESTENV" always false, even when TESTENV is defined

查看:35
本文介绍了"test -v $ TESTENV"即使定义了TESTENV,也始终为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Fedora 27下运行Bash 4.4.19,我有一个简单的脚本:

I'm running Bash 4.4.19, under Fedora 27, and I have a simple script:

#!/bin/bash
TESTENV="Hello"
echo "$TESTENV"
if [ -v $TESTENV ]; then
    echo "Yup"
fi
echo "Done"

运行此命令时,它会打印:

When I run this, it prints:

Hello
./myscript: line 3: [: Hello: binary operator expected
Done

因此,我在第3行添加了多余的括号,现在看起来像这样:

So, I add the extra bracket to line 3, which now looks like:

if [[ -v $TESTENV ]]; then

但是会产生:

Hello
Done

有什么用?我希望以上两者之一都能看到是".我已经尝试将"$ TESTENV" 用引号引起来,并且还尝试了 -z 运算符-但其行为是相同的.

What gives? I expected to see "Yup" for one/both of the above. I've tried wrapping "$TESTENV" in quotes, and I've also tried the -z operator instead - but the behavior is the same.

推荐答案

对于 $ ,您使用的是变量的 value ,而不是变量名本身.您可能是说:

With $, you are using the value of the variable, not the variable name itself. You probably meant:

if [[ -v TESTENV ]]; then
    echo "Yup"
fi


如果您定义了名为 Hello 的变量(例如 Hello = hi ),则 if 条件将会成功,并且您可能没有注意到根本没有问题:)


If you defined variable named Hello (such as Hello=hi) the if condition would have succeeded and you might not have noticed the problem at all :)

这篇关于"test -v $ TESTENV"即使定义了TESTENV,也始终为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆