Unix Shell Script Looping
June 15, 2007 by Mark Marucot
Loops are use to perform certain task multiple times. Using loops helps minimize placing code multiple time performing similar functions. Loops in Unix scripting uses for and while loops.
Do While Loop
The Do While loop takes the following form:
Syntax
CODE:
-
while [ condition ]
-
do
-
# statement
-
done
Example
CODE:
-
#!/bin/sh
-
count=$1 # Initialise count to first parameter
-
while [ $count -gt 0 ] # While count is greater than 5 do
-
do
-
echo “Loop $count” # Display Loop
-
count=$(expr $count -1) # Decrement count by 1
-
done
For While Loop
The For loop takes the following form:
CODE:
-
For variable in word
-
do
-
# statement
-
done
Example
CODE:
-
#!/bin/sh
-
for count in 1 2 3 4 5
-
do
-
echo “Loop $count” # Display Loop
-
done




Comments
Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!