๐ Linux Shell Scripting: Understanding Loop Conditions with Practical Examples

Loops are one of the most important concepts in Shell Scripting. They allow us to execute a block of code repeatedly until a specific condition is met.
In this article, we'll explore for loops and while loops with beginner-friendly examples.
1๏ธโฃ Creating Multiple Files Using a for Loop
This script creates multiple files based on a given range.
Script
#!/bin/bash
# 1 -> Folder/File name
# 2 -> Start range
# 3 -> End range
for (( num=\(2; num<=\)3; num++ ))
do
touch "\(1\)num"
done
Explanation
$1โ File name prefix$2โ Starting number$3โ Ending numbertouchโ Creates an empty filenum++โ Increments the value by 1
Example
bash create_files.sh file 1 5
Output
file1
file2
file3
file4
file5
This script is useful when creating multiple files automatically instead of manually creating them one by one.
2๏ธโฃ Creating Files Using User Input
Instead of passing arguments from the command line, we can ask the user for inputs.
Script
#!/bin/bash
read -p "Enter the file name prefix: " fol
read -p "Enter start range: " start
read -p "Enter end range: " end
for (( num=\(start; num<=\)end; num++ ))
do
touch "\(fol\)num"
done
Example Run
Enter the file name prefix: test
Enter start range: 1
Enter end range: 5
Output
test1
test2
test3
test4
test5
Concepts Used
read -pโ Takes user inputforloop โ Iterates through a rangetouchโ Creates files
3๏ธโฃ Printing Even Numbers Using a while Loop
A while loop executes repeatedly as long as the condition remains true.
Script
#!/bin/bash
num=0
while (( num <= 10 && num % 2 == 0 ))
do
echo $num
((num+=2))
done
Output
0
2
4
6
8
10
Explanation
num=0initializes the variable.num <= 10ensures numbers are printed up to 10.num % 2 == 0checks whether the number is even.((num+=2))increments by 2 to get the next even number.
4๏ธโฃ Printing Odd Numbers Using a while Loop
Script
#!/bin/bash
num=1
while (( num <= 10 && num%2 != 0))
do
echo $num
((num+=2))
done
Output
1
3
5
7
9
Explanation
Since the loop starts with 1 and increments by 2, only odd numbers are printed.
Key Takeaways
โ for loops are best when the number of iterations is known.
โ while loops are useful when execution depends on a condition.
โ
touch can automate file creation tasks.
โ
Arithmetic operations in shell scripting use (( )).
Conclusion
Loops are a fundamental part of Linux Shell Scripting and are widely used in automation, DevOps tasks, system administration, and server management. Mastering for and while loops helps you write efficient scripts, reduce repetitive work, and automate everyday Linux operations.
Start practicing these examples and gradually combine loops with conditions, functions, and file operations to build powerful shell scripts. ๐
Happy Scripting! ๐ง๐ป




