Wednesday, 22 February 2017

Bash 'select' loop - We have been learning about loops in shell scripting and in the recent articles, we have covered two of its kinds - for loop and while loop. In this article, we will be covering another type of a loop - select loop.

Similar to one of the cases in for loop, select loop accepts a sequence of strings/characters separated by whitespace. This sequence of strings is provided as numbered options, just like multiple choice questions, on the terminal screen. You have to select from these options and corresponding command will be run. Lets learn this command in more details.

Basic 'select' Loop

In select loop, we have the similar syntax as that of for loop. As mentioned above, select loop accepts a sequence to iterate through it and present it as a numbered menu. For this, we use the in keywordas shown in below syntax.

In above example, we have provided five strings in the sequence. So, we expect the select to provide these stings in the numbered menu. We then have to select from the choices, one at a time. With each selection, the variable $os will be assigned with the value of the choice we make and echo statement will be executed.

Result:

Which is Your Favorite Linux Distribution..?1) Ubuntu
2) LinuxMint
3) CentOS
4) RedHat
5) Fedora
#? 1
I also like Ubuntu !#? 2
I also like LinuxMint !#? 3
I also like CentOS !#? 4
I also like RedHat !#? 5
I also like Fedora !#? 6
I also like !#? ^C

From above result, we have 3 observations-

The loop is infinite, it will stop only when you press 'Ctrl + C'.

When I entered '6', which is not a valid choice, it will still print something on the screen.

The default prompt is #?, which does not make any sense.

The first two issues can be taken care of with the use of case statement in the select loop. The provision of default value in the case statement comes to the rescue here. We will not cover the case statement here, please check our article on case statement in bash scripting for that. For now, we introduce a case statement in our select loop.

Which Operating System Do You Use..?
1) Ubuntu 3) Windows8 5) WindowsXP
2) LinuxMint 4) Windows7 6) Mac
Enter your choice (must be a number): 1
I also use Ubuntu ..!
Enter your choice (must be a number): 4
Why don't you try Linux..?
Enter your choice (must be a number): 6
You must be Very Rich..!
Enter your choice (must be a number): 9
Invalid option. Program will exit now.

With this, we close our discussion on select loop. In this article, we learned how a basic select loop is constructed, we observed the issues with the basic usage, then to mitigate those we introduced case statement in the loop. We also learned how we can use PS3 variable to set a custom prompt to add values to our program. This is it for this article and stay tuned for more ones. Thanks for stopping by.