Bash For Loop Examples

Question: How do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using for statement? How do I use three-parameter for loop control expression?

Answer: A 'for loop' is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script.

For example, you can run UNIX command or task 5 times or read and process list of files using a for loop. A for loop can be used at a shell prompt or within a shell script itself.

for loop syntax

Numeric ranges for syntax is as follows:

for VARIABLE in 1 2 3 4 5 .. N
do
	command1
	command2
	commandN
done

This type of for loop is characterized by counting. The range is specified by a beginning (#1) and ending number (#5). The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display welcome message 5 times with for loop:

#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

Sometimes you may need to set a step value (allowing one to count by two's or to count backwards for instance). It can be done easily with seq command. A representative example in bash as follows:

#!/bin/bash
for i in $(seq 1 2 20)
do
   echo "Welcome $i times"
done

Latest bash version 3.0+ has inbuilt support for setting up a step value:

#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done

Three-expression bash for loops syntax

This type of for loop share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3).

for (( EXP1; EXP2; EXP3 ))
do
	command1
	command2
	command3
done

A representative three-expression example in bash as follows:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do
	echo "Welcome $c times..."
done

Sample output:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

How do I use for as infinite loops?

Infinite for loop can be created with empty expressions, such as:

#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done

Conditional exit with break

You can do early exit with break statement inside the for loop. You can exit from within a FOR, WHILE or UNTIL loop using break. General break statement inside the for loop:

for I in 1 2 3 4 5
done
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (disaster-condition)
  then
	break       	   #Abandon the loop.
  fi
  statements3          #While good and, no disaster-condition.
done

Following shell script will go though all files stored in /etc directory. The for loop will be abandon when /etc/resolv.conf file found.

#!/bin/bash
for file in /etc/*
do
	if [ "${file}" == "/etc/resolv.conf" ]
	then
		countNameservers=$(grep -c nameserver /etc/resolv.conf)
		echo "Total  ${countNameservers} nameservers defined in ${file}"
		break
	fi
done

Early continuation with continue statement

To resume the next iteration of the enclosing FOR, WHILE or UNTIL loop use continue statement.

for I in 1 2 3 4 5
done
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done

This script make backup of all file names specified on command line. If .bak file exists, it will skip the cp command.

#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
	if [ -f ${f}.bak ]
	then
		echo "Skiping $f file..."
		continue  # read next file and skip cp command
	fi
        # we are hear means no backup file exists, just use cp command to copy file
	/bin/cp $f $f.bak
done

Further readings:

  • See all sample for loop shell script in our bash shell directory.
  • man bash
  • help for
  • help {
  • help break
  • help continue
Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 13 comments… read them below or add one }

1 Jadu Saikia 11.02.08 at 3:37 pm

Nice one. All the examples are explained well, thanks Vivek.

seq 1 2 20
output can also be produced using jot

jot – 1 20 2

The infinite loops as everyone knows have the following alternatives.

while(true)
or
while :

//Jadu

2 Sean 11.04.08 at 2:20 am

The last example can also be produced without the ” in $FILES”:

#!/bin/sh

for f
do

# For-Loop body

done

If the ” in …” is excluded, the loop will run as if “in $@” was given.

3 Andreas 11.13.08 at 4:53 am

Nice explanation tutorial.

4 Manish 11.25.08 at 6:33 am

hey vivek i tried the following syntax for for loop suggested by u but both dint work…
1.
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo “Welcome $c times…”
done

2.
#!/bin/bash
for i in {1..5}
do
echo “Welcome $i times”
done

got error for both the syntax
1. unexpected ‘(’
2. it printed welcome {1..5} times instead repeating it…

help..?

5 lascost 12.06.08 at 6:15 pm

i tried the last example but i seen dint work

#!/bin/bash 

set -x

FILLES="$@"
CP=$(which cp)
for f in $FILES
do
        if [ -f ${f}.bak ]
        then
                echo "skiping $f file"
                continue # read netxt file and skip cp command
        fi
        $CP $f $f.bak
done

i would like know where is the error

6 Vivek Gite 12.13.08 at 4:56 pm

Replace

FILLES="$@"

With

FILES="$@"
7 lo2y 01.28.09 at 10:10 am

hi guys . can any one help me . i need a script to check the file /var/log/messages every 10 minutes .and if its has the following log :
ext3_orphan_cleanup: deleting unreferenced

to apply the following command
sendsms to wut ever .

thnx alot

8 swatkat 02.12.09 at 2:06 pm

i would like to breakk a csv file depending upon two criteria.

1. SIngle file should not be more than 100 lines
2. The third column if has same value on the 100th line as that of the 101th line, the complete line should be included in the 2nd file.
so., now, 1st file will have 99 lines and 2nd file will have 100 lines, ifthe above 2nd condition does not repeats.,

9 archana 03.16.09 at 11:53 pm

for file in $(ls 0902*0010202.TLG); do
day=$(echo $file | cut -c 1-6)
grep ^203 $file | cut -d, -f3 | sort | uniq -c | while read line; do
cnt=$(echo $line | cut -d” ” -f1)
acct=$(echo $line | cut -d” ” -f2)
echo “Date 20${day} Account ${acct} had ${cnt} 203’s” >> Feb_report.txt
done
done

when i run it it gives me a syntax error
ins@ARTMGA01> ./arc.sh
./arc.sh: syntax error at line 4: `$’ unexpected

could you help

10 Navneet 04.20.09 at 10:57 am

Good examples!! easily understood

11 firmit 06.07.09 at 5:06 pm

Hi

How do I read line by line in a file, and use these in a loop? I have a file I read in (cmd max_cpu):
firefox 15
conky 1
cmds=$(cat file)
But $cmds now consist of n items, all being “equal” – it does not split on each line to a new array. I expected that by looping over $cmds, I’d get a 2D array…. I did not.

Otherwise, excellent tutorial!

12 Vivek Gite 06.07.09 at 5:56 pm

Try:

FILE=/etc/passwd
while read line
do
	# store field 1
	F1=$(echo $line|cut -d$FS -f1)
	# store field 2
	F2=$(echo $line|cut -d$FS -f6)
	# store field
	F3=$(echo $line|cut -d$FS -f7)
	echo "User \"$F1\" home directory is $F2 and login shell is $F3"
done < $FILE
13 firmit 06.07.09 at 6:03 pm

Excellent! Thanks Vivek.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tagged as: , , , , , , , , ,

Previous post: Upgrade Ubuntu Hardy Heron Server 8.04 To Ubuntu Server 8.10 Intrepid Ibex

Next post: Edit a File When You Are Viewing It Using more / less Command