How do I use the builtin bash select command in a shell script?
-
Also see: builtin help select
The select builtin is useful for creating menus.
select choice in earth water fire wind; do case $REPLY in 1) echo "You picked $choice" ;; 2) echo "You picked $choice" ;; 3) echo "You picked $choice" ;; 4) echo "You picked $choice" ;; esac done
Running the script given the following results:
$ ./select.sh 1) earth 2) water 3) fire 4) wind #? 2 You picked water #? 4 You picked wind #?
Additional things to improve the functionality.
- The
#?
is the value of PS3 prompt. This can be more readable. - There is no option to quit from a user perspective.
- You might want to do something more useful than echoing a line.
- Clear the terminal.
- Make the output more readable with line spacing.
- Give the user valid options when an incorrect option is selected.
Title the menu.
The script below uses the select command and the case command.
PS3="Your Selection: " clear echo "Operator Menu" echo "=============" select choice in who uptime date "quit menu"; do case $REPLY in 1) "$choice" echo "" ;; 2) "$choice" echo "" ;; 3) "$choice" echo "" ;; 4) echo -e "Quitting menu\n" break ;; *) echo -e "Valid options are 1, 2, 3 or 4\n" ;; esac done
Running the script gives the following results:
Operator Menu ============= 1) who 2) uptime 3) date 4) quit menu Your Selection: 1 training pts/0 2020-06-28 06:21 (192.168.0.122) Your Selection: 3 Sun 28 Jun 07:47:33 EDT 2020 Your Selection: y Valid options are 1, 2, 3, or 4 Your Selection: 4 Quitting menu
- The
© Lightnetics 2024