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:
selectname[inlist] dostatements 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; ...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.
Read now
Unlock full access