Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads