Reputation: 501
I have a while loop in shell and it does not terminate even though it has a break condition, this piece of code run well in other languages but i can't figure out how while loop runs in shell script. Here is my code:
NAME=""
while [[ $NAME != "q" || $NAME != "Q" ]]
do
read NAME
//do something
done
Upvotes: 0
Views: 165
Reputation: 881423
$NAME != "q" || $NAME != "Q"
Unless NAME
can exist in a strange " Schrödinger's cat" sort of state where it can be both Q
and q
at the same time, this expression will always be true.
Think about it:
NAME
is neither q
nor Q
, both sub-expressions will be true so the full expression will be true.Q
, then the first sub-expressions will be true, leading to the full expression being true as well.q
, then the second sub-expressions will be true, leading to the full expression being true as well.What you probably need is:
$NAME != "q" && $NAME != "Q"
Of course, if it's bash
that you're using, it provides a way to uppercase and lowercase a string to make these comparisons easier:
while [[ "${NAME^^}" != "Q" ]] ; # upper-case variant
while [[ "${NAME,,}" != "q" ]] ; # lower-case variant
Upvotes: 1