How To Use Slect In Bash.
In this tutorial, we will cover the basics of the select construct in Bash.
The select construct allows you to generate menus.
Bash select Construct
The select construct generates a menu from a list of items. It has almost the same syntax as the for loop:
The [LIST] can be a series of strings separated by spaces, a range of numbers, output of a command, an array, and so on. A custom prompt for the select construct can be set using the PS3 environment variable .
When the select construct is invoked, each item from the list is printed on the screen (standard error), preceded with a number.
If the user enters a number that corresponds to the number of one of the displayed items, then the value of [ITEM] is set to that item. The value of the selected item is stored in the variable REPLY. Otherwise, if the user input is empty, the prompt and the menu list are displayed again.
The select loop will continue to run and prompt for user input until the break command is executed.
To demonstrate how the select construct works, let’s take a look at the following simple example:
The script will display a menu consisting of list items with an accompanying number and the 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 of if statements.
Let’s take a look at a more practical example. It is a simple calculator that prompt the user for input and performs basic arithmetic operations like addition, subtraction, multiplication, and division.
When the script is executed, it displays the menu and the PS3 prompt. The user is prompted to select the operation and then to enter two numbers. Depending on the user’s input, the scrip will print the result. The user will be asked to perform a new operation after each selection until the break command is executed.
One drawback of this script is that it can work only with integers.
Here is a little more advanced version. We are using the bc tool that supports floating numbers to perform mathematical calculations. Also, the repetitive code is grouped inside a function .
The select construct allows you to easily generate menus. It is especially useful when writing shell scripts that require user input.