Bash Select construct is used to create a numbered menu from the list of items. That is helpful for shell scripts that required user selection across multiple items.
Syntax
The select statement has a similar syntax as ‘for loop’ and it is:
select ITEM in [List] do [commands] done
Here the List can be an array, a range of numbers, a series of strings separated by space, the output of a command, etc. And when the select construct will be invoked, each item from the list will be printed with a numbered sequence. The construct will continue to run until the break command is executed.
Bash Select Example
Let’s understand the select construct with an example. Here we have created a bash script named brand.sh and the select command is used to retrieve the data from the list as a menu. The script will first print the name of all the brands in the list and then it will ask the user to choose any one of them and it will print the name of the selected brand.
Run the script with ‘bash brand.sh’. You will see the following output.
Output1) Apple 2) Google 3) Microsoft 4) Amazon 5) Meta #? 1 You have chosen Apple #? 3 You have chosen Microsoft #? ^C
Press CTRL+C to exit.
One More Example
Let’s take another example of the select construct to see how it works with a case statement.
Here we will create a new file named select.sh and once we will run the file, the user will select any item, and then the case statement will match the item with the case value. If no value is matched then ‘Invalid entry’ will print.
Now run the script with bash select.sh and you will see the following output.
Output1) Ubuntu 3) Fedora 5) Windows7 2) LinuxMint 4) Windows8 6) WindowsXP #? 1 I also use Ubuntu. #? 2 I also use LinuxMint. #? 4 Why don't you try Linux? #? 7 Invalid entry.
Conclusion
This guide explains to use of the select command in bash scripting.
4 Comments
That is fantastic, I was creating a menu in bash and this was perfect. Specifically looping if the incorrect option was used on input.
these scripts dont seem to work on debian or ubuntu. on arch they work, i get “select: not found” and “Syntax error: “do” unexpected”
Hi Jason, Make sure you are using the “bash” command to run the script not “sh”.
or
This information was needful.