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:
  1. while [ condition ]
  2. do
  3. # statement
  4. done

Example

CODE:
  1. #!/bin/sh
  2. count=$1 # Initialise count to first parameter
  3. while [ $count -gt 0 ] # While count is greater than 5 do
  4. do
  5. echo “Loop $count” # Display Loop
  6. count=$(expr $count -1) # Decrement count by 1
  7. done

For While Loop

The For loop takes the following form:

CODE:
  1. For variable in word
  2. do
  3. # statement
  4. done

Example

CODE:
  1. #!/bin/sh
  2. for count in 1 2 3 4 5
  3. do
  4. echo “Loop $count” # Display Loop
  5. done

Related Posts

Comments

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