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]
done
for element in collection:
    loop body
for (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]
done
while condtion:
    loop body
while (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
done

Save the above code to the for-loop.sh file and exit the editor.

Run the command bash for-loop.sh:

for-loop

Bonus

You can also loop through an array of items:

#!/bin/bash

OperatingSystem=("Linux" "Microsoft" "Apple")

for string in ${OperatingSystem[@]}
do
        echo $string
done

For 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
done

Save the above code to the for-loop-if-else.sh file and exit the editor.

Run the command bash for-loop-if-else.sh:

for-loop-condition

While Loop

Create a new file called while-loop.sh

#!/bin/bash

number=0

while [ $number -lt 10 ]
do
    echo $number
    ((number++))
done

Save the above code to the while-loop.sh file and exit the editor.

Run the command bash while-loop.sh:

while-loop

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
done

Save the above code to the while-loop-if.sh file and exit the editor.

Run the command bash while-loop-if.sh:

while-if-loop

Recap:

  • For loop
    • For loop with conditional statement
  • While loop
    • While loop with conditional statement