Linux - Bash Loops

Bash shell can repeat particular instruction again and again, until particular condition satisfies. A group of instruction that is executed repeatedly is called a loop. Bash supports:

    The for loop
    The while loop

Each and every loop must:

  • First, the variable used in loop condition must be initialized, then execution of the loop begins.
  • A test (condition) is made at the beginning of each iteration.
  • The body of loop ends with a statement that modifies the value of the test (condition) variable.
  • Repeatedly execute a block of statements.

The for loop syntax

The for loop syntax is as follows:

            for var in item1 item2 ... itemN
            do
                    command1
                    command2
                    ....
                    ...
                    commandN
            done

The for loop numerical explicit list syntax:

            for var in list-of-values
            do
                    command1
                    command2
                    ....
                    ...
                    commandN
            done

The for loop explicit file list syntax:

            for var in file1 file2 file3 fileN
            do
                    command1
                    command2
                    ....
                    ...
                    commandN
            done

The for loop variable's contents syntax:

            for var in $fileNames
            do
                    command1
                    command2
                    ....
                    ...
                    commandN
            done

The for loop command substitution syntax:

            for var in $(Linux-command-name)
            do
                    command1
                    command2
                    ....
                    ...
                    commandN
            done

The for loop explicit file list using bash array syntax:

            # define an array   
            ArrayName=(~/.config/*.conf)
            for var in "${ArrayName[@]}" 
            do
                    command1 on $var
                    command2
                    ....
                    ...
                    commandN
            done

The for loop three-expression syntax ( this type of for loop share a common heritage with the C programming language ):

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

The above syntax 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).

More about the for loop

The for loop execute a command line once for every new value assigned to a var (variable) in specified list (item1...itemN) i.e. repeat all statement between do and done till condition is not satisfied. The lists or values are normally:

  1. Strings
  2. Numbers
  3. Command line arguments
  4. File names
  5. Linux command output

Example

Create a shell script called testforloop.sh:

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

Save and close the file. Run it as follows:

chmod +x testforloop.sh
./testforloop.sh

The for loop first creates i variable and assigned a number to i from the list of number from 1 to 5. The shell execute echo statement for each assignment of i. This is known as iteration. This process will continue until all the items in the list were not finished. See bash for loop examples page for more information.

The For Loop Using Strings

Create a shell script called forcars.sh

#!/bin/bash
# A simple shell script to print list of cars
for car in bmw ford toyota nissan
   do
   echo "Value of car is: $car"
done

Another example, create a shell script called forcmds.sh:

#!/bin/bash
# A simple shell script to run commands 
for command in date pwd df 
   do
   echo
   echo "*** The output of $command command >"
   #run command 
   $command
   echo
done

Save and close the file. Run it as follows:

chmod +x forcmds.sh
./forcmds.sh

Sample outputs:

*** The output of date command >
Sun Sep  6 14:32:41 IST 2009


*** The output of pwd command >
/1.5/share/data/songs


*** The output of df command >
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sdb2             96116904  27589760  63644592  31% /
tmpfs                  4149972         0   4149972   0% /lib/init/rw
varrun                 4149972       272   4149700   1% /var/run
varlock                4149972         0   4149972   0% /var/lock
udev                   4149972      2808   4147164   1% /dev
tmpfs                  4149972       356   4149616   1% /dev/shm
/dev/sdb5            286374908 274733944  11640964  96% /share
/dev/sdc2            240402848 159452732  68738308  70% /disk1p2
/dev/sda5            1341352436 412128756 861086932  33% /1.5
/dev/sdd1            1442145212  26365188 1342523224   2% /media/backup

The For Loop Using Variable's Contents

Create a shell script called forfilenames.sh

#!/bin/bash
# A shell script to verify user password database
files="/etc/passwd /etc/group /etc/shadow /etc/gshdow"
for f in $files
do
	[  -f $f ] && echo "$f file found" || echo "*** Error - $f file missing."
done

The For Loop Using Command-line Arguments

Create a shell script called forcmdargs.sh:

#!/bin/bash
# A simple shell script to display a file on screen passed as command line argument
[ $# -eq 0 ] && { echo "Usage: $0 file1 file2 fileN"; exit 1; }

# read all command line arguments via the for loop
for f in $*
   do
   echo
   echo "< $f >"
   [ -f $f ] && cat $f || echo "$f not file."
   echo "------------------------------------------------"
done

Save and close the file. Run it as follows:

chmod +x forcmdargs.sh
./forcmdargs.sh /etc/resolv.conf /etc/hostname

Sample outputs:

< /etc/resolv.conf >
nameserver 127.0.0.1
nameserver 4.2.2.1
nameserver 4.2.2.2
------------------------------------------------

< /etc/hostname >
vivek-desktop
------------------------------------------------

The for loop using command substitution

Command substitution is nothing but a shell command output stored in into a string or a variable. The command is a shell command and must be enclosed between grave accents or $(..). The syntax is as follows:

$(command-name)
`command-name`
var=$(command-name)
NOW=$(date)
echo $NOW

Create a shell script called forcmdsub.sh:

#!/bin/bash
echo "Printing file names in /tmp directory:"
for f in $(ls /tmp/*)
do
	echo $f
done

The for loop using ranges or counting

The for loop can be set using the numerical range. The range is specified by a beginning and ending number. 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 multiplication table with for loop (multiplication.sh):

#!/bin/bash
n=$1
# make sure command line arguments are passed to the script
if [ $# -eq 0 ]
then
	echo "A shell script to print multiplication table."
	echo "Usage : $0 number"
	exit 1
fi

# Use for loop
for i in {1..10}
do
	echo "$n * $i = $(( $i * $n))"
done

Save and close the file. Run it as follows:

chmod +x multiplication.sh
./multiplication.sh 
./multiplication.sh 13

Sample outputs:

13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130


Source: https://bash.cyberciti.biz/guide/For_loop