简体   繁体   English

Bash while 循环中的多个条件

[英]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.我试图在使用四个条件的 bash 中获得一个简单的 while 循环,但是在尝试了来自各种论坛的许多不同语法之后,我找不到解决方案。 When i write 'Prod' or 'Dev' or 'Admin', i stay in the loop.当我写“Prod”或“Dev”或“Admin”时,我会留在循环中。

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

You are using ||您正在使用|| where you should be using && ;你应该在哪里使用&& ; no matter what value vmProfil has, at least on of the != conditions must be true.无论vmProfil有什么值,至少!=条件中的一个必须为真。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM