Loops

A loop is a block of code that iterates a list of commands as long as the loop control condition is true.

For Loop

for arg in [list]

This is the basic looping construct. It differs significantly from its C counterpart.

Syntax

for arg in [list]
do 
# command(s)...
done

During each pass through the loop, arg takes on the value of each successive variable in the list.

for arg in "$var1" "$var2" "$var3" ... "$varN" # In pass 1 of the loop, arg = $var1
# In pass 2 of the loop, arg = $var2
# In pass 3 of the loop, arg = $var3
# ...
# In pass N of the loop, arg = $varN

Example

This for loop script will delete all the files that begin with either j or x in the current working directory.

#filename is forrem1.sh
for file in [jx]* do
rm $file
echo ―Removed file \‖$file\‖‖ done

Example

#Symbolic links is a directory save to a file: #file name is listsym.sh
outfile=symlnks.lst
dir=`pwd` # If needed mention other path
echo ―symbolic links in directory \‖$dir\‖‖ > outfile echo ―----― >> ―$outfile‖
for file in `find $dir –type l` do
echo ―$file‖
done | sort >> ―$outfile‖

Example

Script to print multiplication table using for loop

cat > mtable #Script to test for loop
if [ $# -eq 0 ]
then
echo "Error - Number missing from command line argument" echo " Use to print multiplication table for given number"
exit
fi
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done

Save and Run it as

chmod +x mtable
./mtable 7
./mtable

For first run, Above program print multiplication table of given number where i = 1,2 … 10 is multiply by given n (here command line argument 7) in order to produce multiplication table as And for Second run, it will print message -

Error - Number missing form command line argument. This happened because we have not supplied given number for which we want multiplication table.

Using the break Statement

This command exits loops created by the keywords for, while, until, or select.

Syntax

break [n]

If n is specified, it breaks out of n nested loops. The following script checks the list of files x, y, z, none for executable files and prints the first executable file it encounters. If none are executable, file is left set to none but it is not printed.

for file in x y z none 
do
if [ -x $file ]
then
echo $file break;
fi
done

Using the continue Statement

This command skips any lines following it in a for, while, until, or select loop until the next iteration of the loop.

Syntax

continue [n]

If n is specified, then resume execution starting at the nth enclosing loop.

This next script checks for all executable files. If the file is executable the continue statement skips both following echo statements and starts another loop. If the file is not executable, the script prints that it is not executable. If the file is executable, nothing is printed.

for file in x y z 
do
if [ -x $file ]
then
continue;
echo $file is executable 
fi
echo $file is not executable 
done

while loop

This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is true (returns a 0 exit status). In contrast to a for loop, a while loop finds use in situations where the number of loop repetitions is not known beforehand.

while [ condition ] 
do
command(s)...
done

The bracket construct in a while loop is nothing more than our old friend, the test brackets used in an if/then test. In fact, a while loop can legally use the more versatile double brackets construct (while [[condition ]]).

Example

while [ -r "$1" ] 
do
cat $1 >> composite
shift 
done

This example tests the positional parameter to see if it exists and is a readable file. If it is, it appends the contents of the file to the composite file, shifts the positional parameters (what was $2 is now $1) and tests the new file.

When the file is not readable, or there are no more positional parameter values ($1 is null) the while loop is terminated. (Note that without double quotes(") around $1 in the test, the test will respond with an argument expected syntax error when $1=NULL.)

Example

x=0
while [ $x -ne 10 ]
do
let x=x+1
echo $x 
done

This loop initializes the variable x, increments and prints the value until it reaches 10 then exits the loop.

Effect of ‘continue’ in a loop

The following program will print all the numbers from 1 to 20 excluding 3 and 11

Example

limit=19
echo ―printing numbers 1 through 20(but not 3 and 11)‖ a=0
while [ $a –le $limit ]
do
a=`expr $a + 1`
if [ $a –eq 3 ] || [ $a –eq 11 ]
then
continue;
fi
echo –n ―$a ―
done

Until Loop

This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is false (opposite of while loop).

until [ condition-is-false ]
do 
# command(s)...
done

Using the select Statement

It prints on the screen a set of words each preceded by a number. It then prints the PS3 prompt and reads into the REPLY variable the line typed by the user.

If the contents of that line is the number of one of the listed words, the value of parameter is set to the corresponding word. (If the line begins with anything else, parameter is set to the null string.)

Then, regardless of whether the user’s input matches one of the words, the command lines execute. (Within command lines, conditionals can trap the non-matches.) If the user presses Return but has input nothing, the command reprompts for input. The loop continues until it encounters a break.

Subscribe For More Content