The select is a loop used in bash scripting that provides a prompt and a menu of numbered items, a user can select from these options. If the user enters a valid option it executes the code written for that option. If the user presses enter without choosing an option then it will display the menu again. The select command is generally used with the case command.
In this article, you will see the usage of the Linux select loop with some examples.
How to use the select loop in Linux
The following is the syntax of the select loop in Linux.
select ITEM in [LIST] do [commands] done
[LIST] can be a string separated by spaces, range of numbers, array or output of a command, etc. For every selection, a set of commands will be executed within the loop. Originally this loop was introduced in ksh but later adopted in bash.
Examples of bash select loop in Linux
A few examples of select loop used in Linux are given below.
In this example, we will write a simple bash script where the user will enter the number corresponding to a menu item and in output, you will get the item name.
#! /bin/bash # Author : Lalit Kumar # Copyright(c) : explorelinux.com PS3="Enter a number: " select phone in samsung mi oppo vivo iphone lava asus do echo "You selected: $phone" echo "And you selected the number: $REPLY" done
After writing this script save it with the name
selectex0.sh or whatever you want. Now use the following command to run this script –
You will see the given output on your terminal –
You can exit from this menu by pressing
The following script also demonstrates the use of a select loop in Linux.
#! /bin/bash # Author : Lalit Kumar # Copyright(c) : explorelinux.com echo "Choose a Linux distribution: " select distro in Ubuntu LinuxMint CentOS RHEL ArchLinux KaliLinux; do case $distro in Ubuntu|LinuxMint|KaliLinux) echo "Uses apt package manager" ;; CentOS|RHEL) echo "Uses Yum package manager" ;; ArchLinux) echo "Uses pacman package manager" ;; *) echo "Invalid entry" break ;; esac done
Save and execute this script as we did in the previous example.
Now you will see a menu on your terminal you can select among the given options it will give output accordingly.
This is how you can use the select loop in bash scripting in Linux. In case you have a query then leave it in the comments below.