
In this tutorial, we will cover the basics of the select construct in Bash. The select construct allows you to generate menus.
Bash select constructs
The select construct generates a menu from a list of items. It has almost the same syntax as the for loop.
[LIST] can be a series of strings separated by spaces, number ranges, command output, arrays, etc. Custom prompts for select constructs can be set using the PS3 environment variable.
When the select construct is called, each item in the list will be printed on the screen (standard error) with a number.
If the number entered by the user corresponds to the number of one of the displayed items, the value of [ITEM] is set to that item. The value of the selected option is stored in the variable REPLY. Otherwise, if the user input is empty, the prompt and menu list are displayed again.
The select loop will continue to run and prompt the user for input until the break command is executed.
To demonstrate how the select construct works, let’s look at the following simple example.
The script will display a menu consisting of a list of items with accompanying numbers and a PS3 prompt. When the user enters a number, the script will print the selected character and number.
Bash select example
Usually, select is used in combination with case in an if expression.
Let’s look at a more practical example. It is a simple calculator that prompts the user for input and performs basic arithmetic operations, such as addition, subtraction, multiplication, and division.
|
|
After executing the script, the menu and the PS3 prompt will be displayed. The user is prompted to select an action and then enter two numbers. Based on the user’s input, the script will print the result. After each selection, the user will be asked to perform a new action until the break command is executed.
|
|
One drawback of this script is that it can only be used with integers.
Here is a more advanced version. We use the bc tool, which supports floating point numbers, to perform mathematical calculations. Again, the repetition code is grouped in the function.
|
|
Conclusion
The select construct allows you to easily generate menus. It is especially useful when writing shell scripts that require user input.