我试图了解bash中if
和while
语句的编码之间的区别。
在下面的脚本中,如果我使用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
答案 0 :(得分:1)
您的do
个关键字非常错位。
while
和do
之间的所有内容都是条件列表。
所以第一个区块中的条件列表是
[[ ${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