Search code examples
bashshell

How to check for one of multiple accepted options in bash?


I am trying to validate the value of an input variable, and prompt the user for valid value, until I get a valid input ('1' or '2'). I've tried:

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

How this can be done in bash?


Solution

  • The classical way is:

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

    but a cleaner way is to use a case statement:

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