I'm creating a simple bash script and I want to create a select menu in it, like this:
$./script
echo "Choose your option:"
1) Option 1
2) Option 2
3) Option 3
4) Quit
And according to user's choice, I want different actions to be executed. I'm a bash shell scripting noob, I've searched the web for some answers, but got nothing really concrete.
Best Answer
Add
break
statements wherever you need theselect
loop to exit. If abreak
is not performed, theselect
statement loops and the menu is re-displayed.In the third option, I included variables that are set by the
select
statement to demonstrate that you have access to those values. If you choose it, it will output:You can see that
$REPLY
contains the string you entered at the prompt. It is used as an index into the array${options[@]}
as if the array were 1 based. The variable$opt
contains the string from that index in the array.Note that the choices could be a simple list directly in the
select
statement like this:but you can't put such a list in a scalar variable because of the spaces in one of the choices.
You can also use file globbing if you are choosing among files: