Example of bash loops
Here are some examples of Bash loops:
**For Loop**
A For loop is used to iterate over a sequence (like an array) and execute a block of code
for each item in the sequence.
bash
fruits=(apple banana orange)
for fruit in "${fruits[@]}"; do
echo "The current fruit is: $fruit"
done
Output:
The current fruit is: apple
The current fruit is: banana
The current fruit is: orange
**While Loop**
A While loop continues to execute a block of code as long as the condition specified in
its test expression is true.
bash
i=0
while [ $i -lt 5 ]; do
echo "Iteration $i"
((i++))
done
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
**Until Loop**
An Until loop is similar to a While loop, but it continues to execute a block of code as
long as the condition specified in its test expression is false.
bash
i=0
until [ $i -eq 5 ]; do
echo "Iteration $i"
((i++))
done
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
**For-Each Loop**
A For-each loop is used to iterate over an array and execute a block of code for each
item in the array.
bash
colors=(red green blue)
for color in "${colors[@]}"; do
echo "The current color is: $color"
done
Output:
The current color is: red
The current color is: green
The current color is: blue
**For-In Loop**
A For-in loop is used to iterate over an associative array (or a hash table) and execute
a block of code for each key-value pair in the array.
bash
declare -A person=(["name"]="John" ["age"]="30")
for name in "${!person[@]}"; do
echo "The current key is: $name"
echo "The value for this key is: ${person[$name]}"
done
Output:
The current key is: name
The value for this key is: John
The current key is: age
The value for this key is: 30