In this tutorial, we're using loops in bash.
Loops are one of the most powerful features in Bash scripting, enabling you to automate repetitive tasks efficiently. In this tutorial, we will explore three primary types of loops in Bash: for, while, and until. Additionally, we'll provide practical examples to help you understand how to loop over files and numbers.
for Loop
The for loop is ideal for iterating over a set of values, such as files in a directory or a sequence of numbers. It allows you to perform an action for each item in a list.
Syntax
for variable in list; do
command(s)
done
Example: Looping Through Files
Suppose you want to iterate through all .txt
files in a directory and display their names:
#!/bin/bash
for file in *.txt; do
echo "Processing file: $file"
done
Example: Looping Over a Range of Numbers
You can use a range of numbers with the for loop:
#!/bin/bash
for i in {1..5}; do
echo "Number: $i"
done
To include steps (e.g., increment by 2):
for i in {1..10..2}; do
echo "Number: $i"
done
while Loop
The while loop executes as long as the specified condition is true. This type of loop is useful when the number of iterations is not predetermined.
Syntax
while [ condition ]; do
command(s)
done
Example: Countdown Timer
Create a simple countdown timer:
#!/bin/bash
count=10
while [ $count -gt 0 ]; do
echo "Countdown: $count"
count=$((count - 1))
sleep 1
done
echo "Blast off!"
Example: Reading a File Line by Line
#!/bin/bash
while IFS= read -r line; do
echo "Line: $line"
done < input.txt
until Loop
The until loop is the opposite of the while loop; it executes as long as the condition is false.
Syntax
until [ condition ]; do
command(s)
done
Example: Increment Until a Condition is Met
#!/bin/bash
counter=1
until [ $counter -gt 5 ]; do
echo "Counter: $counter"
counter=$((counter + 1))
done
Practical Examples
Example 1: Batch Renaming Files
Imagine you want to rename all .log files in a directory by appending the current date to their names:
#!/bin/bash
date=$(date +%Y-%m-%d)
for file in *.log; do
mv "$file" "${file%.log}_$date.log"
done
Example 2: Generating a Sequence of Directories
Create a set of directories named dir1, dir2, ..., dir10:
#!/bin/bash
for i in {1..10}; do
mkdir "dir$i"
done
Example 3: Monitoring Disk Usage
Continuously monitor disk usage until it drops below a certain threshold:
#!/bin/bash
threshold=80
while :; do
usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$usage" -lt "$threshold" ]; then
echo "Disk usage is below $threshold%."
break
fi
echo "Disk usage is at $usage%. Waiting..."
sleep 10
done
Using loops in Bash provides immense flexibility for handling repetitive tasks efficiently. Practice these examples and experiment with your scripts to deepen your understanding of how loops work.