Bash For Loop Examples In Linux

Updated: Apr 1

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.



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



41 views

Join our newsletter. Get a free Linux account on Cloud.

Never miss a post!

Want a free Linux account?  This account can be used to login to our cloud server and practice Linux commands.

 
kamateravps.gif
topbackgroud.png

✔ Linux Commands   ✔ Linux Skills    ✔ LinuxPerformance   ✔ Linux Interview

Some articles are from the public internet. If you find your article misused or undesired here and you don't want us to display it, please let us know and we'll remove it immediately.