Open In App

Shell Scripting – Select Loop

Last Updated : 04 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The select loop is one of the categories of loops in bash programming. A select-loop in the shell can be stopped in two cases only if there is a break statement or a keyboard interrupt. The main objective of using a select loop is that it represents different data elements in the form of a numbered list to the user. The user can easily select one of the options as listed by the program.

 The syntax of a general select loop is given below,

Syntax:

select myVariable in variable1 variable2 ... variableN
do
    # body to be executed for 
    # every value in the sequence.
done

Here, myVariable is a variable that is used to refer to each of the values from variable1 to variableN.

Example 1:

In the below program we are creating a numbered menu to allow a user (or Btech student) to select the department. 

Source Code:

# Program to demonstrate the working of a 
# select-loop in shell scripting

# PS3="Enter your choice ==> "
# echo "What is your department?"
 
select department in CS IT ECE EE
do
  case $department in

     CS)
        echo "I am from CS department."
        ;;

 IT)
        echo "I am from IT department."
     ;;

      ECE)
        echo "I am from ECE department."
     ;;

 EE)
        echo "I am from EE department."
     ;;

     none)
        break
     ;;

     *) echo "Invalid selection"
     ;;
  esac
done

Output:

Example 2:

In the below program we are creating a numbered menu to allow a user to select a number. Once a number is selected by the user we are displaying whether the number is even or odd.  

Source Code:

# Program to demonstrate the working of
# a select-loop in shell scripting

# PS3="Enter your choice ==> "
# echo "Choose a number:"
  
select num in 1 2 3 4 5 6 7
do
   case $num in
      2|4|6|8) 
         echo "Even number."
         ;;
      1|3|5|7)
         echo "Odd number."
      ;;
      none) 
         break 
      ;;
      *) echo "ERROR: Invalid selection" 
      ;;
   esac
done

Output:

Select loop with input prompts:

We can prompt users before asking for any selection from the menu with the help of the PS3 variable in bash programming. This variable must be declared before the select loop. The value or string with which a PS3 variable is initialized is used to prompt the user on the console. 

Example 1:

In the below program we have prompted the user as “Enter your choice ==>”.

Source Code:

# Program to demonstrate the working of a 
# select-loop in shell scripting

PS3="Enter your choice ==> "
echo "What is your department?"
  
select department in CS IT ECE EE
do
   case $department in

      CS) 
         echo "I am from CS department."
         ;;

        IT)
         echo "I am from IT department."
      ;;

       ECE)
         echo "I am from ECE department."
      ;;

        EE)
         echo "I am from EE department."
      ;;
 
      none) 
         break 
      ;;

      *) echo "Invalid selection" 
      ;;
   esac
done

Output:

Example 2:

In this program, we have prompted the user as “Enter your choice ==>”.

Source Code:

# Program to demonstrate the working of a 
# select-loop in shell scripting

PS3="Enter your choice ==> "
echo "Choose a number:"
  
select num in 1 2 3 4 5 6 7
do
   case $num in
      2|4|6|8) 
         echo "Even number."
         ;;
      1|3|5|7)
         echo "Odd number."
      ;;
      none) 
         break 
      ;;
      *) echo "ERROR: Invalid selection" 
      ;;
   esac
done

Output:

Pipe out options to a select loop in bash

When the end of file (EOF) of input is reached then the select loop gets completed in bash. But in the case of a command piped out to our script the output of the previous command becomes the input for the current command.

Let us understand what does a pipe command means in bash. The pipe is considered one of the most powerful operators in the shell. It is denoted by the symbol (|). The pipe takes the output from one command and uses it as input for another. And, we’re not limited to a single piped command but we can stack them as many times as you like, or until you run out of output or file descriptors. But in the case of select-loop using a pipe out command may lead to no output as demonstrated in the below program.  

Example:

Source Code:

# Program to demonstrate the working of a 
# select-loop in shell scripting

# script: select-loop-bash.sh
select department in CS IT ECE EE
do
   case $department in

      CS) 
         echo "I am from CS department."
         ;;

        IT)
         echo "I am from IT department."
      ;;

       ECE)
         echo "I am from ECE department."
      ;;

        EE)
         echo "I am from EE department."
      ;;
 
      none) 
         break 
      ;;

      *) echo "Invalid selection" 
      ;;
   esac
done

Interactive commands (one after the another) and the output:

Piped:

How to fix no output while using the pipe out command?

This issue can be fixed by ensuring that the select menu will be read from the “/dev/tty” and that we are passing the option with proper word delimiter by using either the “echo” or the “printf” commands.

Example:

Source Code:

# Program to demonstrate the working of a 
# select-loop in shell scripting

# script: select-loop-bash.sh
select department in CS IT ECE EE
do
   case $department in

      CS) 
         echo "I am from CS department."
         ;;

        IT)
         echo "I am from IT department."
      ;;

       ECE)
         echo "I am from ECE department."
      ;;

        EE)
         echo "I am from EE department."
      ;;
 
      none) 
         break 
      ;;

      *) echo "Invalid selection" 
      ;;
   esac
done < /dev/tty

Interactive commands (one after the another) and the output:



Similar Reads

Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has fe
3 min read
Shell Scripting - Restricted Shell
Shell is one of the most important and powerful tools available in GNU/Linux-based systems. One can control the entire system if used correctly, this exact feature makes the shell a double-edged sword. It can potentially harm the system if one executes a system command without knowing its underlying details and consequences. To prevent this we use
5 min read
Shell Scripting - Interactive and Non-Interactive Shell
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Default Shell Variable Value
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Shell Signals Values
Prerequisites: Processes, Bash Scripting, Shell Function Library Signals help the operating system to communicate with processes and vice-versa. Signals are also generated when processes don't function properly or try to access prohibited memory. Different signals are mapped to different numbers which are referred to as signal values. The Linux OS
6 min read
Introduction to Linux Shell and Shell Scripting
If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understanding shell scripting we have to get familiar with th
7 min read
Shell Scripting - Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing
6 min read
Shell Script to Show the Difference Between echo “$SHELL” and echo ‘$SHELL’
In shell scripting and Linux, the echo command is used to display text on the terminal or console. When used with the $SHELL variable, which contains the path of the current user's shell program, the output of the echo command can be different depending on whether the variable is enclosed in single or double quotes. echo "$SHELL" will expand the $S
4 min read
Bash Scripting - How to Run Bash Scripting in Terminal
In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a t
2 min read
Bash Scripting - Working of Bash Scripting
Bash Scripting is a crucial component of Linux's process automation. You can write a series of commands in a file and then execute them using scripting. A Bash script is a plain text file with a set of commands inside of it. These commands are a combination of ones we typically type on the command line ourselves (like ls or cp, for instance) and ot
6 min read
Bash Scripting - Introduction to Bash and Bash Scripting
Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System.  It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to a
10 min read
Array Basics Shell Scripting | Set 2 (Using Loops)
It is recommended to go through Array Basics Shell Scripting | Set-1 Introduction Suppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop and while loop. To Print the Static Array in Bash 1. By Using whi
3 min read
How to check if a directory or a file exists in system or not using Shell Scripting?
Shell scripting is really a powerful and dynamic way to automate your tasks. To test if a directory or file already exists in the system or not we can use shell scripting for the same along with test command. To proceed with the test script lets first check the test manual. To open a manual use the man command as follows: man test Right now we will
2 min read
Create a password generator using shell scripting
Creating a strong password is often a time-consuming task and even after creating a good password by yourself it gets brute-forced by hackers. In this article, we will learn how to create a strong password which fulfills all requirements including symbols, capitals length etc using a simple shell script in Linux. How to create a password generator
1 min read
Leap Year Program with Bash Shell Scripting in Windows
Accurately the Earth has 365.24 days per year, to correct the approximation and keep track of the Solar Calendar the idea of leap year has been introduced to Gregorian Calendar. A leap year comes once every four years. In contrast, it has 366 days with regular years, having 365 days. Mathematical approach to check:Every year is a Leap year if it is
1 min read
String Manipulation in Shell Scripting
String Manipulation is defined as performing several operations on a string resulting change in its contents. In Shell Scripting, this can be done in two ways: pure bash string manipulation, and string manipulation via external commands. Basics of pure bash string manipulation: 1. Assigning content to a variable and printing its content: In bash, '
4 min read
Shell Scripting - Test Constructs
Since 0 by UNIX tradition denotes "success," an if/then construct checks to see if the exit status of a list of commands is 0 and, if it is, runs one or more instructions. There is an exclusive command called [ (left bracket special character). It is a built-in synonym for test and is used for efficiency. This command uses the arguments as file tes
6 min read
Shell Scripting - Define #!/bin/bash
A shell provides an interface to connect with the system. When we use an operating system, we indirectly interact with the shell. While using a terminal every time on any Linux distribution system, we interact with the shell. The main function of the shell is to interpret or analyze Unix commands. A shell takes commands from the user and translates
3 min read
Shell Scripting - Command Substitution
A shell is an interface that helps users to connect with the system. Using a shell is equivalent to indirectly communicating with the operating system. In Linux distributed systems, each time we use the terminal, we connect with a shell. The job of a shell is to analyze Unix commands or instructions given by the user. This process involves taking c
4 min read
Shell Scripting - Substitution
There are certain expressions that convey special meanings. In other words, they are not what they look like. A shell carries out substitution whenever it encounters such expressions. Hence, substitution is defined as a mechanism carried out by a shell in which it substitutes the value of an expression with its actual value. Escape sequences: An es
3 min read
Shell Scripting - True Command
A shell provides an interface with the help of which users can interact with the system easily. To directly interact with a shell, we use an operating system. On a Unix-based operating system, every time we write a command using a terminal, we interact with the system. To interpret or analyze Unix commands, we use a shell. The main job of a shell i
3 min read
Shell Scripting - Variable Substitution
A shell is an interface that helps users to connect with the system. Using a shell is equivalent to indirectly communicating with the operating system. In Linux distributed systems, each time we use a terminal, we connect with a shell. The job of a shell is to analyze Unix commands or instructions given by the user. This process involves taking com
3 min read
Shell Scripting - Rules for Naming Variable Name
Variables are quite important in any script or program, so we need to understand what is the convention to name these variables. There are certain rules and standards to keep in mind while giving names to the variables in Shell scripting. In this article, we will discuss and list down all the rules and conventions to declare a variable name in Shel
4 min read
Shell Scripting - How to view Processes?
In this article, let's explore how we can view current processes running on a Linux Server. Linux machine gives users the option of multitasking hence naturally there will be multiple processes running on a session and also these processes are important fundamental components of Linux OS, Hence System Administrators may need to be aware of all proc
4 min read
Shell Scripting - Dialog Boxes
In this article, we will create a shell script that generates a Dialog Box with GUI generating a message to the user. What is a Dialog Box? A Dialog Box is a temporary window an application runs to convey important information to the users. These dialog boxes can be used to display warnings, errors, and also any additional inputs needed by the syst
7 min read
Shell Scripting - Readonly Command
In this tutorial, we will learn about the ‘readonly’ command. Using the readonly command, you can assign a particular value to a variable that can neither be changed nor modified by subsequent assignments nor be unset. Syntax:readonly name[=value] readonly [-aAf] [name[=value] Most used options: -p : It prints all the defined readonly variables-f :
3 min read
Shell Scripting - Umask Command
A Shell script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a re-usability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands on
3 min read
Shell Scripting - Decision Making
A Shell script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a re-usability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands on
7 min read
Shell Scripting - Disown Command
Shell is a command language interpreter. It is used in most of the UNIX/LINUX-based distros. Shell support scripting means we can automate the Shell commands by writing some scripts with different logic, looping, and decision making. This benefits us to automate some time-consuming and tedious jobs. Here in this article, we are going to discuss the
3 min read
Shell Scripting - How to send Signal to a Processes
Signals allow the operating system to communicate with programs(or processes). There are about 30 standard signals implemented by the Linux OS. We can send signals to processes via certain keyword strokes or by the kill or wait command. Prerequisites: Processes, Bash Scripting, Shell Function Library Sending signals to foreground processes Go to th
4 min read
Article Tags :
three90RightbarBannerImg