sreekutty
Devops

Why Are ‘For’ Loops Necessary? Basic Syntax of Bash ‘For’ Loop Using Bash ‘For’ Loop Looping through Files and Directories Iterating over a Range of Numbers Using ‘for’ with Command Substitution Nested ‘for’ Loops
Without loops, performing an action on 100 different files would require you to type 100 separate commands. Loops are necessary because they:
Eliminate human error : Manually typing filenames often leads to typos.
Save Time : You write the logic once, and the computer handles the volume.
Enable Scalability: A loop that works for 5 files will work exactly the same way for 5,000 files.
The structure of a Bash loop follows a strict "Header, Do, and Done" format.
for variable in list
do
do
command1
command2
done
variable: A temporary name (like item or f) that represents the current object being processed.
list: The collection of items (strings, numbers, or files) the loop will cycle through.
do / done: These keywords act as brackets, containing all the code that should be repeated.
In its simplest form, you can provide a manual list of strings. The loop will assign each string to the variable one by one.
for color in red green blue
do
echo "The current color is $color"
done
This is the most common use case for system administrators. By using wildcards (like *), you can tell Bash to find every file that matches a pattern.
Bash
#Example: Rename all .txt files to .bak
for file in *.txt
do
mv "$file" "${file%.txt}.bak"
done
Note: Always use double quotes "$file" to handle filenames that contain spaces.
If you need to perform an action a specific number of times, you can use curly brace expansion {start..end}.
Bash
#Create folders named folder1 through folder5
for i in {1..5}
do
mkdir "folder$i"
done
You can use the output of another command as the list for your loop. This is done using the $(command) syntax.
Bash
#Loop through all users listed in the system
for user in $(cut -d: -f1 /etc/passwd)
do
echo "Found system user: $user"
done
A nested loop is a loop inside another loop. The "inner" loop will complete its entire cycle for every single step of the "outer" loop. This is useful for creating grids or processing multi-layered data.
Bash
for letter in A B
do
for number in 1 2
do
echo "Combination: $letter$number"
done
done
Output:
Combination: A1
Combination: A2
Combination: B1
Combination: B2
Share this article
Loading comments...
© 2026 CloudHouse Technologies Pvt.Ltd. All rights reserved.