Loops
Looping with Bash
Similar to other programming languages like Java, JavaScript, and Python you are also able to write for loops in bash:
for item in [LIST]
do
[COMMANDS]
donefor element in collection:
loop bodyfor (Virable Initialization; Loop Exit Condition; Variable Modification) {
loop body
}for (Variable Initialization; Loop Exit Condition; Variable Modification) {
loop body
}You can also write while loops:
while [CONDITION]
do
[COMMANDS]
donewhile condtion:
loop bodywhile (condition) {
loop body
}while (condition) {
loop body
}Note
Notice that bash requires a closing done statement to end the loop.
Examples
For Loop
Create a new file called for-loop.sh
#!/bin/bash
for string in "Linux" "Microsoft" "Apple"
do
echo $string
doneSave the above code to the for-loop.sh file and exit the editor.
Run the command bash for-loop.sh:
Bonus
You can also loop through an array of items:
#!/bin/bash
OperatingSystem=("Linux" "Microsoft" "Apple")
for string in ${OperatingSystem[@]}
do
echo $string
doneFor Loop with Condition
Create a new file called for-loop-if-else.sh
#!/bin/bash
OperatingSystem=("Linux" "Microsoft" "Apple")
for string in ${OperatingSystem[@]}
do
if [[ $string == "Linux" ]]
then
echo $string: "Open Source!"
else
echo $string: "Not Open Source : ("
fi
doneSave the above code to the for-loop-if-else.sh file and exit the editor.
Run the command bash for-loop-if-else.sh:
While Loop
Create a new file called while-loop.sh
#!/bin/bash
number=0
while [ $number -lt 10 ]
do
echo $number
((number++))
doneSave the above code to the while-loop.sh file and exit the editor.
Run the command bash while-loop.sh:
While Loop with Condition
Create a new file called while-loop-if.sh
#!/bin/bash
number=0
while [ $number -lt 10 ]
do
echo $number
((number++))
if [[ $number -eq 5 ]]
then
echo "halfway done!"
fi
doneSave the above code to the while-loop-if.sh file and exit the editor.
Run the command bash while-loop-if.sh:
Recap:
- For loop
- For loop with conditional statement
- While loop
- While loop with conditional statement



