0

I'm trying to get a simple while loop working in bash that uses four conditions, but after trying many different syntax from various forums, I can't find solution. When i write 'Prod' or 'Dev' or 'Admin', i stay in the loop.

while [ -z $vmProfil ] || [ $vmProfil != 'Prod' ] || [ $vmProfil != "Dev" ] || [ $vmProfil != "Admin" ]
do 
    read -p 'Choose vm profil between Prod, Dev or Admin :' vmProfil
done
0

1 Answer 1

3

You are using || where you should be using &&; no matter what value vmProfil has, at least on of the != conditions must be true.

while [ -z "$vmProfil" ] || { [ "$vmProfil" != 'Prod' ] && [ "$vmProfil" != "Dev" ] && [ "$vmProfil" != "Admin" ]; }

You can also check negate the result of checking if any condition is true.

while [ -z "$vmProfil" ] || ! { [ "$vmProfil" = 'Prod' ] || [ "$vmProfil" = "Dev" ] || [ "$vmProfil" = "Admin" ]; }

I would write this as an infinite loop with an explicit break, though.

while :; do
  read -p '...' vmProfil
  case $vmProfil in
    Prod|Dev|Admin) break ;;
  esac
done
Sign up to request clarification or add additional context in comments.

6 Comments

I think you got the logic backwards from the question: "When i write 'Prod' or 'Dev' or 'Admin', i stay in the loop."
That's what the OP's code does now, which is the opposite of what the prompt implies they want.
You are correct. OP's logic in the question is backwards. The logic he is attempting to do in his code was right. +1
Also, the unquoted variables are a possible problem, especially in [ -z $vmProfil ]-- it'll probably work, but mostly by accident. Double-quote variable references to avoid weird parsing problems.
Thanks to the quoting "$vmProfil" the first check -z "$vmProfil" is redundant. I do like the case solution, +1
|

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.