The Bash while loop is a powerful control structure that allows you to repeatedly execute commands as long as a specified condition remains true. It is widely used for tasks such as automating processes, reading files line by line, handling user input, and evaluating command-line options.
This guide will cover basic and advanced examples of the Bash while loop, including infinite loops, breaking loops, reading files, and handling user input.
Basic Syntax of a While Loop in Bash
The syntax of a while loop is as follows:
while [ condition ]
do
command1
command2
command3
doneCode language: JavaScript (javascript)
- The loop continues executing the commands inside the
doblock until the condition evaluates tofalse. - The condition is typically a comparison statement or a command output.
- If the condition never becomes false, it creates an infinite loop.
One-liner Syntax:
while [ condition ]; do commands; doneCode language: JavaScript (javascript)
Example 1: Printing a Message Multiple Times
The following script prints “Welcome X times” five times:
#!/bin/bash
x=1
while [ $x -le 5 ]
do
echo "Welcome $x times"
x=$(( x + 1 ))
doneCode language: PHP (php)
One-liner equivalent:
x=1; while [ $x -le 5 ]; do echo "Welcome $x times"; x=$(( x + 1 )); doneCode language: PHP (php)
Example 2: Factorial Calculation Using a While Loop
This script calculates the factorial of a given number:
#!/bin/bash
counter=$1
factorial=1
# Check if the user provided a number
if [ -z "$counter" ]; then
echo "Syntax: $0 <number>"
exit 1
fi
# Compute factorial
while [ $counter -gt 0 ]
do
factorial=$(( factorial * counter ))
counter=$(( counter - 1 ))
done
echo "Factorial: $factorial"Code language: PHP (php)
Usage:
$ chmod +x factorial.sh
$ ./factorial.sh 5
Example 3: Reading a File Line by Line
One of the most common use cases for a while loop is reading a file line by line:
#!/bin/bash
FILE="$1"
if [ -z "$FILE" ]; then
echo "Syntax: $0 <filename>"
exit 1
fi
# Read the file line by line
while IFS= read -r line
do
echo "$line"
done < "$FILE"Code language: PHP (php)
Usage:
$ chmod +x read_file.sh
$ ./read_file.sh myfile.txt
Example 4: Handling Command-Line Options with getopts
This example shows how to process command-line options using a while loop and getopts:
while getopts "ae:f:hd:s:qx:" option
do
case "${option}" in
a) ALARM="TRUE";;
e) ADMIN=${OPTARG};;
d) DOMAIN=${OPTARG};;
f) SERVERFILE=${OPTARG};;
s) WHOIS_SERVER=${OPTARG};;
q) QUIET="TRUE";;
x) WARNDAYS=${OPTARG};;
\?) echo "Invalid option"; exit 1;;
esac
doneCode language: PHP (php)
This script allows handling multiple options with flags and arguments.
Example 5: Processing User Input in an Infinite Loop
You can use an infinite while loop to keep asking for user input:
#!/bin/bash
while :
do
echo "Enter two numbers (or -1 to quit):"
read a b
if [ "$a" -eq -1 ]; then
echo "Exiting..."
break
fi
result=$(( a + b ))
echo "Sum: $result"
doneCode language: PHP (php)
Example 6: Blocking IP Addresses from a File
The following script reads a list of IP addresses from a file and blocks them using iptables:
#!/bin/bash
IFS='#' # Set Internal Field Separator to #
INPUT="blocked_ips.txt"
while read -r ip comment
do
/sbin/iptables -A INPUT -s "$ip" -m comment --comment "$comment" -j DROP
done < "$INPUT"Code language: PHP (php)
Example file (blocked_ips.txt):
192.168.1.50#BLOCK:www-2
180.110.1.6#BLOCK:hacker
99.99.99.99#BLOCK:spammerCode language: CSS (css)
This script parses the file and applies firewall rules accordingly.
Example 7: Breaking a Loop with break
The break statement terminates a loop when a condition is met:
#!/bin/bash
counter=1
while [ $counter -le 10 ]
do
if [ $counter -eq 5 ]; then
echo "Breaking loop at $counter"
break
fi
echo "Counter: $counter"
counter=$(( counter + 1 ))
doneCode language: PHP (php)
Output:
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Breaking loop at 5
Example 8: Skipping Iterations with continue
The continue statement skips the current iteration and jumps to the next one:
#!/bin/bash
counter=0
while [ $counter -lt 10 ]
do
counter=$(( counter + 1 ))
if [ $(( counter % 2 )) -eq 0 ]; then
continue
fi
echo "Odd number: $counter"
doneCode language: JavaScript (javascript)
This script only prints odd numbers.
Summary: Key Takeaways
- While loops execute commands as long as the condition is true.
- Use
breakto exit a loop early. - Use
continueto skip an iteration. - Infinite loops can be created with
while :(useCTRL+Cto stop). - While loops are useful for reading files, processing user input, automating tasks, and managing system processes.
Recommended Readings
If you want to dive deeper into Bash scripting, check out these resources:
- Bash Shell Scripting Guide
- Linux Bash For Loop Examples
- Run
man bashorhelp whilein your terminal for documentation.
