0

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
2
  • 1
    NAME is always not "q" or not "Q". For example, "q" is not "Q"; "Q" is not "q"; and "x" is neither "q" nor "Q". You want &&, not ||. (This would behave identically in other languages, the error is purely logical.) Commented Mar 5, 2019 at 2:14
  • @Amadan yes thank you very much, code in shell looks different from others, i get it now. Commented Mar 5, 2019 at 2:16

1 Answer 1

1
$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:

  • If NAME is neither q nor Q, both sub-expressions will be true so the full expression will be true.
  • If it's Q, then the first sub-expressions will be true, leading to the full expression being true as well.
  • If it's 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
Sign up to request clarification or add additional context in comments.

1 Comment

Or you could use [[ $NAME != [Qq] ]]

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.