## 📝 Author
Birat Aryal — birataryal.github.io
Created Date: 2025-06-23
Updated Date: Monday 23rd June 2025 08:17:52
Website - birataryal.com.np
Repository - Birat Aryal
LinkedIn - Birat Aryal
DevSecOps Engineer | System Engineer | Cyber Security Analyst | Network Engineer
🔁 Bash for Loops
The for loop in Bash is used to iterate over a list of items, numeric ranges, or file patterns.
📐 Basic Syntax
Bash
for variable in list
do
# commands
done
✅ Common Examples
1. Loop Over a List of Words
Bash
#!/bin/bash
for name in Alice Bob Charlie
do
echo "Hello, $name!"
done
2. Loop Over a Range of Numbers (Brace Expansion)
Bash
#!/bin/bash
for i in {1..5}
do
echo "Number: $i"
done
3. Loop Over Files
Bash
#!/bin/bash
for file in *.txt
do
echo "Found file: $file"
done
4. Loop Over Command Output
Bash
#!/bin/bash
for user in $(cut -d: -f1 /etc/passwd)
do
echo "User: $user"
done
🧱 Nested for Loops
Bash
#!/bin/bash
for i in 1 2 3
do
for j in a b
do
echo "i=$i, j=$j"
done
done
⛔ Loop Control: break & continue
Example: Skip an Item with continue
Bash
for i in {1..5}
do
if [ $i -eq 3 ]; then
continue
fi
echo "i=$i"
done
Example: Exit Early with break
Bash
for i in {1..5}
do
if [ $i -eq 3 ]; then
break
fi
echo "i=$i"
done
🔄 Combining with Conditionals
Bash
#!/bin/bash
for i in {1..10}
do
if (( i % 2 == 0 )); then
echo "$i is even"
else
echo "$i is odd"
fi
done
📦 Loop Over Arguments ($@)
Bash
#!/bin/bash
for arg in "$@"
do
echo "Argument: $arg"
done
Run with:
Bash
./script.sh apple banana cherry
🧠 Tips
-
Use quotes (
"$var") to handle spaces -
Use
[[ ... ]]for safer condition checks -
Use
set -xto debug loop behavior