bash while循环比较不评估

时间:2015-03-04 00:08:36

标签: bash comparison operators

我试图了解bash中ifwhile语句的编码之间的区别。 在下面的脚本中,如果我使用IF,我会使用==-eq等获得预期结果。但是对于while循环,每个while似乎都评估为真试验。而循环1& 3应该失败,对吗?

A != B, 
A == B,
A == C

我尝试了[ "" "" ][[ "" "" ]]等的不同组合。

while

的正确语法是什么

THX 领域

#!/bin/sh
set -x
myVarA="abc"
myVarB="abc"
myVarC="def"

while [[ ${myVarA} != ${myVarB} ]]
    echo "A does not equal B"
    i=$(($i+1))
    do sleep 1s
    break
done

while [[ ${myVarA} == ${myVarB} ]]
    echo "A does equal B"
    i=$(($i+1))
    do sleep 1s
    break
done

while [[ ${myVarA} == ${myVarC} ]]
    echo "A does equal C"
    i=$(($i+1))
    do sleep 1s
    break
done

呈现以下内容,

+ myVarA=abc
+ myVarB=abc
+ myVarC=def
+ [[ abc != abc ]]
+ echo 'A does not equal B'
A does not equal B
+ i=1
+ sleep 1s
+ break
+ [[ abc == abc ]]
+ echo 'A does equal B'
A does equal B
+ i=2
+ sleep 1s
+ break
+ [[ abc == def ]]
+ echo 'A does equal C'
A does equal C
+ i=3
+ sleep 1s
+ break

1 个答案:

答案 0 :(得分:1)

您的do个关键字非常错位。

whiledo之间的所有内容都是条件列表。

所以第一个区块中的条件列表是

[[ ${myVarA} != ${myVarB} ]]; echo "A does not equal B"; i=$(($i+1))

,正如您可能想象的那样,评估为true,因为i=$(($i+1))评估为true

与其他街区类似。

do移至while

的末尾
while [[ ${myVarA} != ${myVarB} ]]; do
    : do something
done