Ascalonian
Ascalonian

Reputation: 15174

Get wildcard value from bash case statement

I am wondering how to get the value from a case wildcard? I have an array that generates a menu for me. I then have a case that determines which option is chosen. The last part of the case statement is the wildcard value. I am looking to get the value used for the wildcard.

Here is the code that I am using:

menu=()
menu+=('Option 1')
menu+=('Option 2')
menu+=('Option 3')
menu+=('Option 4')
menu+=('Quit')

echo "What would you like to install?"
echo " "
select opt in "${menu[@]}"
do
    case $opt in
        'Option 1' )
            echo "Doing Option 1"
            ;;
        'Option 2' )
            echo "Doing Option 2"
            ;;
        'Option 3' )
            echo "Doing Option 3"
            ;;
        'Option 4' )
            echo "Doing Option 4"
            ;;
        'Quit' )
            echo "Quitting installations"
            exit;
            ;;
        * )
            echo "Invalid input: ${opt}"
            ;;
    esac
done

In the above, the "Invalid input" value is always empty. I can enter "foobar" as the option and it does not show. I have also change the variable to just $opt but it still doesn't print out.

Upvotes: 4

Views: 1069

Answers (1)

e0k
e0k

Reputation: 7161

From man bash:

select name [ in word ] ; do list ; done

The list of words following in is expanded, generating a list of items. The set of expanded words is printed on the standard error, each preceded by a number. If the in word is omitted, the positional parameters are printed (see PARAMETERS below). The PS3 prompt is then displayed and a line read from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the command completes. Any other value read causes name to be set to null. The line read is saved in the variable REPLY. The list is executed after each selection until a break command is executed. The exit status of select is the exit status of the last command executed in list, or zero if no commands were executed.

So just change your

    * )
        echo "Invalid input: ${opt}"
        ;;

to

    * )
        echo "Invalid input: ${REPLY}"
        ;;

Upvotes: 6

Related Questions