Select Statements in Bash
Shell scripts often need a menu so that the user can interact with the script and choose options. An easy way to so this is with the “select” statement.
Syntax:
select selection_var [in list]; do statements (can use selection_var) done |
Example:
echo "########################################"; echo "# SELECTS EXAMPLE - TheLinuxBlog.Com #"; echo "########################################"; echo "# Please Choose an Option #"; echo "########################################"; select selection_var in Number_1 This_is_Choice_2 Exit; do case $selection_var in Number_1 ) echo "You picked $selection_var or #$REPLY" ;; This_is_Choice_2 ) echo "You picked $selection_var or #$REPLY" ;; Exit ) echo Goodbye! break ;; * ) echo "Invalid Selection" ;; esac done |
This bash select example has three choices. The first two are just examples, the third exits the script. There is a fourth case but it is not a choice, it tells the user that they have entered an invalid selection. I recommend using a case inside of a select because it will make life easier when adding onto a script. The $REPLY variable is returned from the select statement as a means of knowing what number was pressed. The $REPLY variable can be used in the case statement but I avoid doing so as all of the case blocks will have to be rearranged every time a new option is added.
The select statement in bash is very easy to implement and it can add a whole new range of functionality into your scripts. So try them out and look out for them in future shell scripts from The Linux Blog.














