Skip to Content

10 Bash For Loop Examples In Linux

Bash for loop is a commonly used statement in Linux bash script. For loop is used to execute a series of commands until a particular condition becomes false. Today we are going to learn some basic bash for loop examples.

What is bash for loop?

Bash-for loop is a control structure that allows you to repeat a certain set of commands multiple times. You can use it to quickly and easily iterate through arrays, files, or any other type of data. It is a powerful tool that you need to perform the same action on multiple items.

  • Bash For Loop over strings
  • Bash For Loop over a number range
  • Bash For Loop over array elements
  • Bash For Loop over command result

 

The keywords for bash for loop are for in do done. The following is the syntax.

for i in (list)
do
command1
command2
done

We can also use bash for loop in one-liner like this.

for i in (list); do commands; done

Bash For Loop over strings

The loop will iterate over each item in the list of strings, and the variable element will be set to the current item.

# for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus
do
echo $planet
done

Bash For Loop over a number range

We can use the sequence expression to specify a range of numbers or characters by defining a start and the end point of the range.

  1. seq start end
  2. {start..end}

All the following for loop example iterates through all numbers from 0 to 3.

for i in {0..3}
do
echo “Number: $i”
done

for i in $(seq 0 3)
do
echo “Number: $i”
done

for i in `seq 0 3`
do
echo “Number: $i”
done

This is the output.

Number: 0
Number: 1
Number: 2
Number: 3

Bash For Loop over array elements

We can use the for loop to iterate over an array of elements. In the example below, we are defining an array named myArray and iterating over each element of the array.

myArray=(1 2 3)

$ for value in “${myArray[@]}”; do echo “$value”; done
1
2
3

$ for value in “${myArray[*]}”; do echo “$value”; done
1 2 3

Bash For Loop over command result

We can use the for loop to iterate over command result items. The following two examples iterate the ls command output.

for i in `ls`; do echo $i;done
CEPS
Client
Service
X11
cisco

$ for i in $(ls); do echo $i;done
CEPS
Client
Service
X11
cisco

Linux Troubleshooting Guide:

Linux Learning Guide: