select

All of the flow-control constructs we have seen so far are also available in the Bourne shell, and the C shell has equivalents with different syntax. Our next construct, select, is available only in the Korn shell and bash; [72]moreover, it has no analogy in conventional programming languages.

select allows you to generate simple menus easily. It has concise syntax, but it does quite a lot of work. The syntax is:

select name
             [in 
            list
            ]
do
   
            statements that can use 
            $name...
done

This is the same syntax as for except for the keyword select. And like for, you can omit the in list and it will default to "$@“, i.e., the list of quoted command-line arguments. Here is what select does:

  • Generates a menu of each item in list, formatted with numbers for each choice

  • Prompts the user for a number

  • Stores the selected choice in the variable name and the selected number in the built-in variable REPLY

  • Executes the statements in the body

  • Repeats the process forever (but see below for how to exit)

Here is a task that adds another command to our pushd and popd utilities.

The display and selection of directories is best handled by using select. We can start off with something along the lines of: [73]

selectd () { PS3='directory? ' select selection in $DIR_STACK; ...

Get Learning the bash Shell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.