Bash非零测试用例(-n),[和[[做不同的事情 [英] Bash nonzero test case (-n), [ and [[ are doing different things

查看:88
本文介绍了Bash非零测试用例(-n),[和[[做不同的事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我仅将[[用于各种测试用例,因为这是最先进的方法,并且使用起来更安全(Regex,...). 我知道[[与[执行不同的代码,但是根据联机帮助页和各种文档,它至少应以相同的方式处理"-n"之类的选项,但实际上并非如此.

Usually i only use [[ for all kinds of test cases, because it's the most advanced way and it's more safe to use (Regex, ...). I know that [[ executes different code than [, but according to the manpage and various documentations, it should at least handle options like "-n" the same way, but it doesn't.

-n STRING STRING的长度非零

-n STRING the length of STRING is nonzero

VAR=

if [[ -n $VAR ]]
then
        echo "\$VAR is nonzero"
else
        echo "\$VAR is zero"
fi

$ VAR为零

VAR=

if [ -n $VAR ]
then
        echo "\$VAR is nonzero"
else
        echo "\$VAR is zero"
fi

$ VAR非零

这怎么可能?

bash 4.1.2(1)

bash 4.1.2(1)

推荐答案

我认为您的问题与引号有关.

I think that your problem is related to quotes.

当您使用[ -n $VAR ]时,所执行的命令将不包含$VAR应该位于的任何参数.

When you use [ -n $VAR ] the command that is executed won't contain any argument where $VAR should be:

$ set -x
$ [ -n $VAR ]
+ '[' -n ']'

这意味着您实际上正在测试字符串-n是否为非空,因为以下两个测试是等效的:

This means that you are essentially testing whether the string -n is non-empty, because the following two tests are equivalent:

[ string ]    # is a shorthand for
[ -n string ] # which is always true!

如果使用引号,则会得到不同的行为:

If you use quotes, then you get different behaviour:

$ [ -n "$VAR" ]
+ '[' -n '' ']'

现在,您正在测试变量是否为非空,以便获得预期的行为.

Now you are testing whether the variable is non-empty, so you get the expected behaviour.

这篇关于Bash非零测试用例(-n),[和[[做不同的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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