0

I am trying to understand the difference between coding for if and while statements in bash. 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. While loops 1 & 3 should fail, correct?

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

I have tried different combinations of [ "" "" ] or [[ "" "" ]] etc.

What is the correct syntax for 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
2
  • 1
    The do part of your while loops are a few lines down the block. Possibly you should move them up to the beginning, i.e. while [[ condition ]]; do Commented Mar 4, 2015 at 0:16
  • @Tom, thanks for the lead, the answer below explained the wile condition extends until the :do and that I did not understand. thanks Art Commented Mar 4, 2015 at 0:39

1 Answer 1

1

Your do keywords are wildly misplaced.

Everything between while and do is the condition list.

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.

Similarly for the other blocks.

Move the do to the end of the while lines

while [[ ${myVarA} != ${myVarB} ]]; do
    : do something
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.