Google

Shell Scripting

Shell Scripting

Sorted By Creation Time

loops

Home: www.packetnexus.com

#!/bin/bash

#whilefor.sh

count=1
#This is our while loop at the top it checks to see if the current value
#of our variable count is less than or equal to 20.  If it is then the
#two statements within the body of the loop are executed and the test is
#done again.  When the test is failed the while loop ends and execution
#of the program continues right after the done statement

while [ $count -le 20 ]
do
        echo "Number of time through while loop: $count"
        count=$(($count+1))
done

#This is our for loop
#the statement $(ls) tells the shell to execute whatever command is in the
#parentheses.  In our case the ls command.  The for loop will continue
#assigning a value to the file variable until no more file names are sent to
it
#(from the ls command)

for file in $(ls); do
        echo "$file"
done

The syntax of the while loop is:


while condition do
	statements
done

The syntax of a for loop is:

for variable in values
do
	statements
done


The while loop will continue executing the statements in the body of the
loop until the condition at the top is false. The for loop acts a bit
differently. It will continue to assign a value to variable and execute the
body of the loop until there are no more values to assign. The for loop is
most often used to process lists and arrays of data.

There is another looping structure in shell programming, the until statement
and it has the following syntax:



until condition
do
	statements
done


It is so similar to the other loops I will not demonstrate it. It will
continue executing the body of the loop until the condition becomes true. I
will simply rewrite the while loop above using an until:


until [ $count -eq 20 ]
do
        echo "Number of time through while loop: $count"
        count=$(($count+1))
done


This loop will continue until our variable equals 20, go ahead and replace
this until loop with the while loop in the above program and try it out.

Whew, we are finished with control structures, although this barely touches
on the capabilities of the various control structures. Next up is the
conclusion (go ahead and applaud, not for my writing but that the torture is
almost over).


Back to the Index