Foil 04 - Using a counter to control a loop

 1 #!/bin/sh
 2 #*********************************************************************
 3 # Sample of a command repeated for a specified number of iterations. *
 4 #*********************************************************************
 5 
 6 max=4096 ; hash=100
 7 
 8 i=1
 9 while [ "$i" -le "$max" ]
10   do
11 
12     j=`echo "$i" | awk '{ printf "%4.4d",$1 }'`  # Add leading zeros
13 
14     mkfile -n 1m  erase.$j  # The command to execute
15 
16     if [ `expr "$j" % "$hash"` -eq 0 ]
17       then
18         echo "Completed $j"
19       fi
20 
21     i=`expr "$i" + 1`
22   done
23 
24 echo "Completed all $max iterations"                               #04

This sample uses a counter and introduces the while, if, and test commands. It also uses the expr command for arithmetic and awk for functions that the shell can't handle.

  • Lines 9 and 16 use the [] syntax for the test command. See the man page for other options and syntax.
  • Line 8 initializies the loop counter.
  • Line 9 compares the loop counter against the maximum.
  • Line 12 uses the awk command to format a string. Some systems have the printf function available as separate command, but many more don't.
  • Lines 16-19 show how progress messages can be handled.
  • Lines 16 and 21 show arithmatic using the expr command.

    Note the use of -le and -eq for numeric comparisons on the test command. String comparisons use = and != while numeric comparisons use -eq and -ne.

    Use double quotes around variables most of the time. Then if a logic error results in a null value the shell will still see it as "" instead of a missing value, causing a syntax error.

    Previous   Next   Index