Search code examples
linuxbashmenu

How to create a menu with a range of options?


I would like to create a menu in shell script with a range of options. In this case, I want to force the user only to use a range of numbers, e.g. 1 to 5, but without use CASE. If the user choose 6, the menu ask again for the number between the range.

I remember something like:

OPTION (){
    [[ $option = +(1|2|3|4|5) ]] || OPTION
}

Solution

  • Following may help you in same:

    cat choose2.ksh
    check() {
    while [ ! ${finished} ]
    do
    echo "Please enter a digit:"
    read value
    if [[ $value -le 5 ]]
    then
            echo "user entered between 1 to 5."
            finished=1
    else
            echo "user entered more than 5 in this case."
    fi
    done
    }
    
    check
    

    Execution of script:

    ./choose2.ksh
    Please enter a digit:
    12
    user entered more than 5 in this case.
    Please enter a digit:
    12
    user entered more than 5 in this case.
    Please enter a digit:
    1
    user entered between 1 to 5.
    

    So you could see that if user enters other than 1 to 5 than it asks user again a Input else it will simple come out of script(you could do other things too as per your need).