Boris
Boris

Reputation: 1

Bash Multiple conditions in while loop

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

Upvotes: 0

Views: 1804

Answers (1)

chepner
chepner

Reputation: 532333

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

Upvotes: 3

Related Questions