O'Reilly logo

Learning the bash Shell, Second Edition by Bill Rosenblatt, Cameron Newham

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

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

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