Need to loop in Bash? Follow these easy steps:
1. For Loop:
for loop to iterate over a list of items:
#!/bin/bash
for i in {1..5}
do
echo "Iteration $i"
done
2. While Loop:
while loop to repeat commands as long as a condition is true:
#!/bin/bash
counter=1
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++))
done
3. Until Loop:
until loop to repeat commands until a condition becomes true:
#!/bin/bash
counter=1
until [ $counter -gt 5 ]
do
echo "Counter: $counter"
((counter++))
done
4. Loop Through Array:
for loop:
#!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
echo "Fruit: $fruit"
done
Jorge García
Fullstack developer