Bash For Loop (With Examples)

Bash for loop is a bash statement that allows code to be executed repeatedly. Loops can be used at the command line prompt or within a shell script.

Bash for Loop Basic Syntax

The basic syntax of bash for loop is

for <variable> in <list>
   do <commands>
done
  • <list> is a sequence of any values (words, numbers, etc.) separated by spaces.
  • <commands> is a set of any valid Bash command (usually executed over a list of items).
  • for is a loop syntax keyword.
  • <variable> is a bash variable name used to get access to the item from the list.

Here’s a basic bash for loop example.

for VARIABLE in "blue" "green" "red" "orange" "yellow"
   do echo "$VARIABLE"
done
A very basic example of bash for loop.
A basic example of bash for loop.

You can see a list of our variables (blue, green, red, orange, yellow) displayed in the terminal.

Basic Bash For Loop Examples

Strings Example

In this example, we display the days of the work week.

for weekday in Monday Tuesday Wednesday Thursday Friday
   do echo "Day of the week is $weekday"
done
Strings example - bash for loop
Strings example – bash for loop

Range Example

In this example, we count (the range) from 45 to 50.

for num in {45..50}
   do echo "The number is $num"
done
Range example - bash for loop
Range example – bash for loop

Arrays Example

In this example, we iterate through the teams in the nflteams array.

nflteam=('Chiefs' 'Raiders' 'Broncos' 'Chargers')
   for nflteam in "${nflteam[@]}"
    do echo "NFL Team: $nflteam"
done
Array example - bash for loop
Array example – bash for loop

Increments Example

In this example, we count from 0 to 40 in increments of 10.

for num in {0..40..10}
   do echo "The number is $num"
done
Increments example - bash for loop
Increments example – bash for loop

Infinite Loop Example

In this example, we create an infinite loop using an empty expression. The only way to stop the loop is by pressing <Ctrl>C.

for (( ; ; ))
   do echo "This is an infinite loop! [Press CTRL+C to abort]"
done
Infinite loop example -bash for loop
Infinite loop example -bash for loop

Break Statement Example

In this example, we cycle through the letters K through Q and break when we come to the letter O.

for letter in {K..Q}
   do
     if [[ "$letter" == 'O' ]]; then
   break
     fi
echo "The letter is: $letter"
done
Break statement example - bash for loop
Break statement example – bash for loop

Continue Statement Example

In this example, we cycle through the numbers 1 through 10. When we come to the number 5, we skip the number and continue counting until we reach 10.

for num in {1..10}
   do
    if [[ "$num" == '5' ]]; then
   continue
    fi
echo "The number is: $num"
done
Continue statement example - bash for loop
Continue statement example – bash for loop.

Was this article helpful?

Leave a Comment