使用(不在)bash 的 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25527564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:14:28  来源:igfitidea点击:

While loop using (not in) bash

bashshell

提问by Odin

I am trying to have while check the value of an input variable. For example while will only exist if value of option is 1 or 2.

我正在尝试检查输入变量的值。For example while will only exist if value of option is 1 or 2.

while option not in 1 2
do :
    read -p "Please choose an option" option
done

How this can be done in bash?

这如何在 bash 中完成?

[Duplicate] This is not a duplicate because the one marked as duplicate such consider comparing two strings without having multiple options at one end.

[重复] 这不是重复的,因为标记为重复的那个考虑比较两个字符串,而在一端没有多个选项。

回答by William Pursell

The classical way is:

经典的方法是:

while ! { test "$option" = 1 || test "$option" = 2; }; do ...

while ! { test "$option" = 1 || test "$option" = 2; }; do ...

but a cleaner way is to use a case statement:

但更简洁的方法是使用 case 语句:

while :; do
  case "$option" in 
    1|2) break ;;
    *) ... ;;
  esac
done

回答by Lorenzo Marcon

I'd do something like that:

我会做这样的事情:

#!/bin/bash

while : ; do
    echo "Please choose an option"
    read val
    [[ $val != 1 && $val != 2 ]] || break
done

回答by Adrian Frühwirth

Use the selectbuiltin:

使用select内置:

$ cat select.sh
#!/bin/bash

options=("Option 1" "Option 2")

echo "Please choose an option:"
select option in "${options[@]}"; do
        [ -n "${option}" ] && break
done
echo "You picked: ${option}"

?

?

$ ./select.sh
Please choose an option:
1) Option 1
2) Option 2
#? 3
#? xyz
#? 2
You picked: Option 2

回答by chepner

In bash, you can use pattern matching to test $option:

在 中bash,您可以使用模式匹配来测试$option

while [[ $option != [12] ]]; do
    read -p "Please choose an option: " option
done

回答by Cajus Pollmeier

Or if you plan to evaluate more options, use case:

或者,如果您打算评估更多选项,请使用案例:

#!/bin/bash

while true; do
  read -p "Please choose an option" option

  case "$option" in
    [12]) break
          ;;
    *)    echo "whatever"
  esac
done

回答by anubhava

You can use this whilecondition using {...}list construct and shell globbing:

您可以使用列表构造和使用此while条件:{...}shell globbing

option=0

while [[ $(echo {1,2}) != *"$option"* ]]; do
    read -p "Please choose an option: " option
done

回答by anubhava

I think this is the most common way

我认为这是最常见的方式

while [[ "$option" -ne 1 ]]  || [[ "$option" -ne 2 ]]; do
          read -p "Please choose an option" option
done