Voxfor - All rights reserved - 2013-2025
We Accepted





In this article, we will learn about Bash For Loops. Bash is a robust shell used in Linux for executing commands and automating tasks. One of the most valuable features of Bash is the “for loop.” This guide will help you understand how to use for-loops in Bash with simple examples, tips, and best practices.
A for-loop allows you to repeat a set of commands multiple times. It’s beneficial when you want to perform the same action on different items. For example, you can use a for loop to process a list of files, execute a command a certain number of times, or iterate through a series of numbers.
The basic syntax of a for loop in Bash is:
for variable in list
do
commands
done
Let’s start with a simple example that loops through a list of fruits:\
for tech in voxfor vps internet
do
echo "I like $tech"
done
Output:
I like voxfor
I like vps
I like internet
In this example, the loop iterates through each fruit and prints a message.
You can loop through a range of numbers using the seq command. Here’s how:
for number in $(seq 49 55)
do
echo "Number: $number"
done
Output:
Number: 49
Number: 50
Number: 51
Number: 52
Number: 53
Number: 54
Number: 55
Here, seq 49 55 generates the numbers from 1 to 5, and the loop prints each number.
Example 3: Working with Files in a Directory
You can use for-loops to process files in a directory. Here’s an example that lists all .txt files:
for file in *.txt
do
echo "Processing $file"
done
Output:
Processing file1.txt
Processing file2.txt
This loop goes through all .txt files in the current directory and prints a message for each file.
Nested for-loops are helpful in handling more complex tasks. Here’s an example of a multiplication table:
for i in {1..5}
do
for j in {1..5}
do
echo "$i * $
Output:
1 * 1 = 1
1 * 2 = 2
...
5 * 5 = 25
In this case, the outer loop goes through numbers 1 to 5, and the inner loop does the same, creating a multiplication table.
for j in {1..5}; do echo "6 * $j = $((6 * j))" done
Output:
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30
In this case, the outer loop goes through numbers 1 to 5, and the inner loop does the same, creating a multiplication table.
You can also loop through the output of a command. For instance, to list all running processes:
for process in $(ps -e | awk '{print $4}')
do
echo "Process name: $process"
done
Output:
Process name: bash
Process name: sshd
In this example, the loop processes each name of the running processes.
Backup Files: Automate the process of backing up files.
bash
for file in /path/to/source/*; do
cp "$file" /path/to/backup/
done
1. Batch Renaming Files: Rename a group of files with a specific pattern.
bash
for file in *.jpg; do
mv "$file" "${file/.jpg/_backup.jpg}"
done
2. Install Packages: Install multiple packages in one command.
bash
for package in git vim curl; do
sudo apt-get install -y "$package"
done
C-style for Loop: Add a section covering the C-style for loop in bash, which is helpful for arithmetic-based loops.
for ((i=1; i<=5; i++)); do
echo "Number: $i"
done
Working with Arrays: Provide examples that show how to loop through arrays using bash for loops, as arrays are often used in scripts.
arr=("apple" "banana" "cherry")
for fruit in "${arr[@]}"; do
echo "I like $fruit"
done
Working with Functions: Add an example where loops interact with bash functions, demonstrating how to modularize code.
function greet {
echo "Hello $1"
}
for name in Alice Bob Charlie; do
greet $name
done
Advanced Command Substitution: Cover more advanced use cases for command substitution within loops. For example, iterating over dynamically generated file lists using find:
for file in $(find /path/to/dir -name '*.log'); do
echo "Processing $file"
done
Parallel Execution: Explore running loop iterations in parallel to optimize performance using external tools like xargs or GNU Parallel.
Automating System Maintenance: Provide practical scripts that run maintenance tasks like log rotation, disk space monitoring, or service status checking, and explain how for-loops help in these scenarios.
Data Processing: Add an example of how to use for-loops for data processing tasks like parsing CSV files or generating reports.
for line in $(cat data.csv); do
# Process each line
done
By adding these additional fields, your article can offer a more comprehensive and deeper understanding of bash for loops, going beyond the basics while making it more valuable for both beginners and advanced users.
Explain the C-style for loop in bash, often used for arithmetic operations. Provide examples of how to iterate with initialization, condition, and increment all in one line.
for ((i=1; i<=5; i++)); do echo "Number: $i" done
#!/bin/bash
# Define the range for the multiplication table
start=1
end=10
# Print the header
echo "Multiplication Table"
for i in $(seq $start $end); do
for j in $(seq $start $end); do
# Print the product
printf "%4d" $((i * j))
done
echo # New line after each row
done
Explain how bash for loops can iterate over arrays. Include examples of both indexed and associative arrays.
arr=("voxfor" "voxfor1" "voxfor2")
for color in "${arr[@]}"; do
echo "Text: $color"
done
Show how to loop through the output of external commands with command substitution. Include examples of using commands like ls, find, grep, and awk in loops.
for file in $(ls *.txt); do
echo "Processing: $file"
done
Discuss how to use if-else, case, or &&/|| logic inside for loops to make more dynamic scripts. For example, processing different files based on their extensions.
for file in *; do
if [[ $file == *.txt ]]; then
echo "Text file: $file"
fi
done
#!/bin/bash
# Define a function to extract error lines
extract_errors() {
local file="$1" # Filename
local output_file="$2" # Output file for errors
# Extract error lines and append them to the output file
grep "error" "$file" >> "$output_file"
}
# Main script execution
output_file="errors.txt" # Output file to save all errors
> "$output_file" # Clear the output file if it exists
for log_file in *.log; do # Loop through all .log files
extract_errors "$log_file" "$output_file" # Call the function
done
echo "Errors extracted to $output_file"
Discuss how to handle errors within loops using trap for signals or using conditional statements like if and test to catch mistakes and continue or break the loop safely.
for item in *; do
if [[ ! -e $item ]]; then
echo "Error: $item not found"
continue
fi
done
GNU Parallel is a more advanced tool specifically designed for parallel processing. It allows you to run jobs in parallel using multiple CPU cores and can handle complex command execution.
You may need to install GNU Parallel if it’s not already available on your system. On most Linux distributions, you can install it using your package manager:
# For Debian/Ubuntu
sudo apt-get install parallel
# For Red Hat/CentOS
sudo yum install parallel
# For MacOS using Homebrew
brew install parallel
Using GNU Parallel to search for “error” in log files would look like this:
find . -name "*.log" | parallel grep -H "error"
Provide examples of how to loop through a file, processing each line individually. It is beneficial for working with logs, CSV files, or configuration files.
while IFS= read -r line; do
echo "Processing line: $line"
done < file.txt
for file in *.log; do
grep "error" "$file"
done
Add more details about looping through a sequence of numbers using {start..end..step} syntax or the seq command. Explain the different methods of controlling step values and using floating-point numbers.
for i in {1..10..2}; do
echo $i
done
for i in {1..10}; do
if [ "$i" -eq 5 ]; then
echo "Breaking the loop at $i"
break
fi
echo "Current number: $i"
done
set -x # Enable debugging
for i in {1..3}; do
echo "Processing number: $i"
if [ "$i" -eq 2 ]; then
echo "Found number 2"
fi
done
set +x # Disable debugging
while read -r line; do
echo "Line: $line"
done < input.txt
Explain how to loop through arguments passed to a script using the particular variable $@. It is useful when writing scripts that accept multiple file inputs or other arguments.
for arg in "$@"; do
echo "Argument: $arg"
done
#!/bin/bash
# Get the current date
current_date=$(date +%Y-%m-%d)
for i in {0..4}; do
future_date=$(date -d "$current_date + $i week" +%Y-%m-%d)
echo "Date in $i week(s): $future_date"
done
Provide more advanced examples of pattern matching inside loops, using tools like grep, regular expressions, or globbing patterns to filter or process only files or data that match specific conditions.
for file in *.log; do
if grep -q "error" "$file"; then
echo "Error found in $file"
fi
done
Demonstrate how to create interactive loops that take user input and respond dynamically. For example, looping through a series of user prompts, asking for input, and performing actions based on the feedback provided.
for i in {1..3}; do
read -p "Enter a number: " num
echo "You entered: $num"
done
Discuss how to properly handle special characters, such as spaces, newlines, or escape sequences within loops. It is essential when dealing with filenames or data that contain unusual characters.
for file in *; do
if [[ $file == *\ * ]]; then
echo "File has space: $file"
fi
done
Bash for loops is a great way to start shell scripts. Practicing all these examples and tips can help you improve your use of for loops in your daily Linux content. Experiment with different scenarios and use cases to understand their potential fully.
Using for-loops effectively can save you time and effort, making your Linux experience much more efficient. Happy scripting!
Vinayak Baranwal wroteย this article.ย Use the provided link to connect with Vinayak on LinkedIn for more insightful content or collaboration opportunities.