In the world of Bash scripting, the select loop is an approach that enables programmers to create an intuitive, text-based menu for users to navigate through options effortlessly. This loop prompts users to select from a predefined list of options, providing a structured and user-friendly way to interact with a script. It is a swift tool to automate a decision-making task that depends on various criteria. In this article, I will explore the Select loop in Bash and give some examples of this loop.
What is Select Loop in Bash?
The select loop in Bash is used for developing simple text-based menus in scripts. It is a handy tool when programmers ask users to choose one or more items from a list of options. The primary utility of a select loop is that it represents different data elements as an ordered list to the users. Only the break command or the keyboard interruption can stop the execution of a select loop.
Syntax of Select Loop in Bash
The general syntax for select loop in Bash is:
select variable_name in variable1 variable2 ... variableN
do
[commands to be executed]
done
The “select” loop will iterate through each variable of the variable1 variable2 ... variableN
list one by one and execute the command inside the code block for each variable from the variables list.
5 Examples of Select Loop in Bash
In this section, I have listed a few examples of the select loop in bash, such as checking odd-even numbers, setting custom prompts, creating backup and restore scripts, and making the select menu permanent.
1. A Simple Select Loop
The select loop prompts the user to select an option from a predefined list. It automatically converts the list of the element to a numbered menu. Then, execute the commands inside the code block for the selected option.
Here is a bash script containing a simple select loop:
#!/bin/bash
select fav in ubuntu kali fedora mintOS
do
echo "My fav distribution = ${fav}"
break
done
The select fav in ubuntu kali fedora mintOS
command creates a simple menu and prompts the user to select an option from the list provided. It Keeps the choice on the fav variable. Finally, the echo "My fav distribution = ${fav}"
command prints the selected option, and the break command terminates the select loop.
The select loop has printed a text according to the user’s choice.
2. Setting Up a Custom Prompt
User interaction is an essential aspect of scripting. A customized prompt elevates the user experience, making the interaction more intuitive and engaging. A customized prompt guides users to appropriately intend the bash script. Use the syntax to set a specific string as prompts of a select loop: PS3="String_of_customized_prompt"
.
Here is a complete script for setting up a customized prompt:
#!/bin/bash
PS3="Choose your favorite distribution: "
select fav in ubuntu fedora mintOS kali; do
echo "My fav distribution = ${fav}"
break
done
The PS3 variable is set to the prompt message. Then, the loop iterates over the options (ubuntu, fedora, mintOS, kali) and assigns the selected choice to the variable fav. The loop prints a message using the echo command indicating the user’s favourite distribution.
The image shows a customized prompt for the select loop.
3. Checking Whether a Number is Even or Odd
If a number is divisible by 2, it is an even number; otherwise, it is odd. The select loop can quickly do this task. The case should be defined separately for odd and even numbers. To customize the prompt, use the syntax PS3=” Your Text”
. And for defining a case, follow the syntax: case $variable_stored_number in odd_number_range/ even_number_range)
.
Here is a detailed bash script to check a number:
#!/bin/bash
PS3="Your selection ==> "
echo "Please, Choose a number:"
select number in 1 2 3 4 5 6 7 8 9 10 11 12
do
case $number in
2|4|6|8|10|12)
echo "The number you entered is an Even number."
break
;;
1|3|5|7|9|11)
echo "The number you entered is an Odd number."
break
;;
none)
break
;;
*) echo "ERROR: Your selection is Invalid"
;;
esac
done
The PS3 variable has been set to the prompt string for the select statement. After that, the input number is saved as the number variable. Then, the loop iterates through the options and compares whether the input number is odd or even. Consequently, it prints a result on the terminal, and the break command terminates the select loop. The esac
marks the end of the case statement.
The image shows that the script has determined the number as odd.
4. Creating Backup and Restoring Script
Some files contain vital information about system administration and database. The rsync command (remote synchronization) can copy files from one directory to another directory files. This command serves the programmer’s purpose of backing up important files to a secured directory and restoring them whenever necessary.
Here is a complete bash script:
#!/bin/bash
SOURCE="/home/susmit/.bashrc"
DESTINATION="/home/susmit/Documents/"
# This function will take backup
function backup(){
rsync -a --progress --delete-before --info=progress2 ${SOURCE} ${DESTINATION}
}
# This function will restore the backup
function restore(){
rsync -a --progress --delete-before --info=progress2 ${DESTINATION} ${SOURCE}
}
PS3="Choose either BACKUP or RESTORE :: "
select option in backup restore
do
if [[ ${option} = "backup" ]];then
backup
elif [[ ${option} = "restore" ]];then
restore
fi
break
done
The function backup(){ rsync -a --progress --delete-before --info=progress2 ${SOURCE} ${DESTINATION} }
command defines the backup function where the rsync command copies the file from the SOURCE
directory to the DESTINATION
directory. The -a option stands for archive mode, which ensures a comprehensive copy preserving various file attributes, such as permissions, ownership, timestamps, etc. The –-progress option shows the progress of the file transfer.
After that, the –delete-before option ensures the deletion of extraneous files in the destination directory before transferring new files. Thus, the destination becomes the exact copy of the source. The –info=progress2 option specifies the additional information during the transfer.
Similarly, the restore function is defined.
At first, the select loop executes and asks for input from the user. Afterwards, the backup or restore is done according to the user input.
The image shows a successful backup of the SOURCE file.
5. Making the Select Menu Permanent
Putting the select loop inside a while loop and keeping the condition true makes the select menu permanent. The while loop will execute the select loop repeatedly, asking the user to choose from the options.
Here is a practical bash script to make the select menu permanent:
#!/bin/bash
PS3="Select item please: "
options=("option 1" "option 2" "option 3")
while true; do
select option in "${options[@]}" Quit
do
case $REPLY in
1) echo "Selected option #$REPLY which means $option"; break;;
2) echo "Selected option #$REPLY which means $option"; break;;
3) echo "Selected option #$REPLY which means $option"; break;;
$((${#options[@]}+1))) echo "We're done!"; break 2;;
*) echo "Ooops - unknown choice $REPLY"; break;
esac
done
done
Initially, the while loop starts to execute as the condition is true. Then, the select loop asks the user to input from the defined menu or Quit. After taking valid input from the user, the case statement checks the input from the options and prints it on the terminal using the echo command. Finally, the break command terminates the select loop.
In case the input is equal to the length of the options array +1, then the $((${#options[@]}+1))) echo "We're done!"; break 2;;
command prints a farewell message and terminates the select loop. If the input is invalid, the *) echo "Ooops - unknown choice $REPLY"; break;
command prints an error message. The while loop will execute infinite times until “4” is the user input.
The image shows that the select loop has made a permanent menu that refreshes infinite time.
Pipe Out Options to Select Loop in Bash
The pipe command is denoted by a vertical bar (|). This pipe passes output from one command as input to another command. This operation can be carried on from one command to another multiple times. To pass a list of options to a select loop, use the \n1 \n2 \n3 \n4
as a delimiter that represents a new line. Here’s how:
#!/bin/bash
select department in ME NAME CE WRE
do
case $department in
ME)
echo "Hello! I am from ME department."
break
;;
NAME)
echo "Hello! I am from NAME department."
break
;;
CE)
echo "I am from CE department."
break
;;
WRE)
echo "I am from WRE department."
break
;;
none)
break
;;
*) echo "Invalid selection"
;;
esac
done
Now, pass the option with the proper word delimiter from the command line interface.
echo "1) ME\n2) NAME\n3) CE\n4) WRE" | ./script7.sh
The echo "1) ME\n2) NAME\n3) CE\n4) WRE" | ./script7.sh
has passed the list of options ME NAME CE WRE
as the argument of script7.sh. Here, n2, n3,
and n4
specify a new line.
You can use the printf command instead of the echo command.
The image shows that the echo command could not properly pipe options to the select loop.
Fixing No Output While Using the Pipe Out Command
To fix the no output while using the pipe out command, the select menu has to be read from the “/dev/tty”
file that represents the terminal for the current process. For this purpose, add the below line at the bottom of the previous script.
done < /dev/tty
The image shows that the options have properly piped to the select loop.
Conclusion
The select loop in Bash enables us to create a versatile and user-friendly interactive menu in shell scripts. This simplifies user choices in handling input effectively, and this tool elevates the scripting experience. This approach makes the bash script accessible to users with limited coding exposure.
People Also Ask
How do you exit a select loop in Bash?
To exit a select loop in Bash, use the break command or press CTRL+C from the keyboard. It will terminate the loop.
Why do we need loops?
We need loops for the following reasons:
- It helps us to automate repetitive tasks and make our script concise.
- It enables us to traverse over the elements of data structures.
How do you stop an infinite loop in Bash?
To stop the execution of an infinite loop in bash, press the CTRL+C button. It helps programmers to get control over an uncontrolled loop.
How do you exit a loop from a function?
To exit a loop from a function, use the break command in that function. Then, it will skip all the subsequent parts of the loop and jump to the next part of the script.
Related Articles
- For Loop in Bash
- While Loop in Bash
- Until Loop in Bash
- How to Use Loop Control in Bash [Break & Continue Statement]
<< Go Back to Loops in Bash | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners