Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Wednesday, 9 October 2013

Bash Scripting - Select Loop

bash-select-loop

    In some of my recent articles, I've been writing on Loop Statements in Linux Shell Scripting covering basic use of For, While and Until Loops. In these articles, we have seen what loops are, how they work and how they are used in BASH scripts. If you have not read them yet, you can do it now!

    In this article, I will cover an another loop statement - 'Select' Loop. The select loop gives a simple way to generate a numbered menu and from this numbered menu user is asked to select the options. It is helpful when you want the user to select single or multiple options from a list of items

The 'Select' Loop

In any select loop, there will be a variable varName and a list of choices separated by a space. When the user chooses an option from the given choices, the value of the variable varName is set as the value of the selected option.

Syntax:


select varName in choice1 choice2 ... choiceN
do

    -- Block of Commands --
   
done

Example:

#!/bin/bash

echo "Which is Your Favorite Linux Distribution..?"

select os in Ubuntu LinuxMint CentOS RedHat Fedora
do
    echo "I also like $os !" 
done
Result:

Which is Your Favorite Linux Distribution..?
1) Ubuntu
2) LinuxMint
3) CentOS
4) RedHat
5) Fedora

1
I also like Ubuntu !
We can also make use of Case Statement in a Select loop.

Example:

#!/bin/bash

echo "Which Operating System Do You Use..?"

select os in Ubuntu LinuxMint Windows8 Windows7 WindowsXP Mac
do
    case $os in
        "Ubuntu" | "Linux Mint")
            echo "I also use $os ..!"
            ;;

        "Windows8" | "Windows7" | "WindowsXP")
            echo "Why don't you try Linux..?"
            ;;

        "Mac")
            echo "You must be Very Rich..!"
            ;;
    esac
done 
Result:

Which Operating System Do You Use..?
1) Ubuntu      3) Windows8   5) WindowsXP
2) LinuxMint   4) Windows7   6) Mac

4
Why don't you try Linux..?

That's all about Select Loop!

Also Read:

0 comments:

Post a Comment