A very useful tool for menus is called select. It originally comes from the Kornshell, but is also found in bash. One interesting aspect of the select loop is that it has no conditional test at all; the only way out of the loop is to use break or exit. select continuously loops around, displaying a prompt, and sets its variable to the value provided by the loop. It also sets $REPLY to the actual number typed in by the user. If the user presses the ENTER key, select redisplays the list of items accepted by the loop. If an invalid option is typed in by the user, the variable is not set, so you can also easily see if a chosen item was valid or not. The best way to understand select is to see it in action.
$ cat select1.sh #!/bin/bash select item in one two three four five do if [ ! -z "$item" ]; then echo "You chose option number $REPLY which is \"$item\"" else echo "$REPLY is not valid." fi done $ ./select1.sh 1) one 2) two 3) three 4) four 5) five #? 1 You chose option number 1 which is "one" #? 4 You chose option number 4 which is "four" #? (enter) 1) one 2) two 3) three 4) four 5) five #? two two is not valid. #? 6 6 is not valid. #? ^C $
This simple loop tells select what the menu items are (the words “one” to “five” in this case) and all it does is test each time whether or not the $item variable has been set. If so, it is certain to ...