O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Select Loops

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.

download.eps
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
$

select1.sh

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required