Shell Scripting Tutorial
For Loop
- It is an example of looping statement and alternative for while loop
- It is used to execute group of statements based on the looping condition
- Bash supports several examples of for-loops. Some of them below
- Simple for loop
- Range based for loop
- C Style based for loop
- Infinite for loop.
1. Simple for loop (Data based for loop)
- Here the loop is based on the data or collection. The data can be the same type or different type.
Syntax
for variable in data
do
# code
done
Where,
variable is an user defined variable.
Example 1 – Data based for loop
Source Code
echo “——————————–“
echo -e “\t Data based For Loop”
echo “——————————–“
for i in 12 true “Hello” 34.55
do
echo ” $i”
done
Output
2. Range Based for loop
- Here the loop is based on the three attributes like start, stop and interval.
- These attributes should be enclosed by curly braces such as {start..stop..interval }
- Where,
- Start is an inclusive which is the starting range of number
- Stop is an inclusive which is the ending range of number
- Interval is an optional frequency gap, usually it is 1 by default.
Syntax
for variable in {start..stop}
do
# code
done
Where,
variable is an user defined variable.
NOTE
- Interval is an optional in for loop.
- By default, it is 1.
Drawback
- Dynamic value can’t be permitted for attributes like start, stop and interval in the range based for loop
Example 2 – Range based for loop
3. C Style Based For Loop (Three Expression For Loop)
- This is similar to c programming for loop
- It takes three expressions like exp1, exp2, exp3
- Where,
- exp1 is an initial condition
- exp2 is an condition
- exp3 is the either increment or decrement value
Syntax
for ((exp1; exp2; exp3))
do
# code
done
Example 3 – C Style based for loop
Source Code
echo “—————————————“
echo -e “\t C Style Based For loop”
echo “—————————————“
echo “Enter the number: “
read n
f=1
for ((i=1;i<=n;i++))
do
f=$((f*i))
done
echo “Fact is : $f”
Output
4. Infinite For Loop
- If you don’t mention the start, stop and interval in c style loop, it will be considered as infinite for loop
- Like c programming, just specify two semicolons ;; to display the infinite For loop
- We need to press ctrl+c to terminate / stop the loop.
Syntax
for ((;;))
do
# code
done
Example 4 – Infinite For Loop
Source Code
echo “———————————–“
echo -e “\t Infinite For Loop”
echo “———————————–“
# infinite for loop
for ((;;))
do
echo “Good Morning”
done
Output
RELATED POSTS
1. Arrays in Bash Script
2. Strings in Bash Script
3. Command Line Arguments in Shell Script
4. File Test Operators in Bash
5. Switch Case in Bash Script
6. Bash Script – Convert Number to Words
7. Operators in Bash Script
8. Function in Bash Script
9. Command Substitution in Bash
MORE USEFUL TUTORIALS