简体   繁体   English

bash while循环比较不评估

[英]bash while loop comparison not evaluating

I am trying to understand the difference between coding for if and while statements in bash. 我试图理解bash中ifwhile语句的编码之间的区别。 In the script below, if I use IF I get the expected result using == OR -eq etc. However with the while loop each while seems to evaluate as true for all tests. 在下面的脚本中,如果我使用IF ,则可以使用== OR -eq等获得预期的结果。但是,使用while循环while似乎对所有测试都为true。 While loops 1 & 3 should fail, correct? 虽然循环1和3应该失败,对吗?

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

I have tried different combinations of [ "" "" ] or [[ "" "" ]] etc. 我尝试过[ "" "" ][[ "" "" ]]等的不同组合。

What is the correct syntax for while while的正确语法是什么

thx Art 艺术

#!/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

renders the following, 呈现以下内容,

+ 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

Your do keywords are wildly misplaced. do的关键字是疯狂错误的。

Everything between while and do is the condition list. whiledo之间的所有内容都是条件列表。

So your condition list in the first block is 因此,您在第一块中的条件列表是

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

which, as you might imagine, evaluates as true since i=$(($i+1)) evaluates as true . 其中,如你所想,为求true ,因为i=$(($i+1))的计算结果为true

Similarly for the other blocks. 其他块也一样。

Move the do to the end of the while lines do移至while行的末尾

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM