Bash Loops
Bash Loop Statements are used to execute a block of statements repeatedly based on a condition, or execute a block of statements for each element in a collection.
Bash Loops Tutorials
The following tutorials cover looping statements in Bash with detailed explanation and examples.
Other Tutorials using Bash Loops
The following tutorials cover some of the scenarios where bash loops are used.
- Bash While True
Examples
The following examples demonstrate how to use For, While and Until loop statements in bash scripting.
Bash For Loop
In the following script, we use For loop to iterate over elements of an array and execute a set of statement(s) for each item in the array.
Example.sh
arr=( "apple" "banana" "cherry" )
for i in "${arr[@]}"
do
echo "Fruit : $i"
done
Output
Fruit : apple
Fruit : banana
Fruit : cherry
Bash While Loop
In the following script, we use While loop to print numbers from 0 to 9.
Example.sh
count=10
i=0
while [ $i -lt $count ];
do
echo "$i"
let i++
done
Output
0
1
2
3
4
5
6
7
8
9
Bash Until Loop
In the following script, we use for loop to iterate over elements of an array and execute a set of statement(s) for each item in the array.
Example.sh
count=10
i=0
until [ $i -gt $count ];
do
echo "$i"
let i++
done
Output
0
1
2
3
4
5
6
7
8
9
10
Difference Between While and Until Loops
The basic difference between While and Until loops is that: While loop stops when the condition is false, but, Until loop stops when the condition is true.
Conclusion
In this Bash Tutorial, we have learnt about the looping statements in Bash scripting, with examples.