Appendix J. Exercises

J.1. Analyzing Scripts

Examine the following script. Run it, then explain what it does. Annotate the script, then rewrite it in a more compact and elegant manner.

   1 #!/bin/bash
   2 
   3 MAX=10000
   4 
   5 
   6   for((nr=1; nr<$MAX; nr++))
   7   do
   8 
   9     let "t1 = nr % 5"
  10     if [ "$t1" -ne 3 ]
  11     then
  12       continue
  13     fi
  14 
  15     let "t2 = nr % 7"
  16     if [ "$t2" -ne 4 ]
  17     then
  18       continue
  19     fi
  20 
  21     let "t3 = nr % 9"
  22     if [ "$t3" -ne 5 ]
  23     then
  24       continue
  25     fi
  26 
  27   break   # What heppens when you comment out this line? Why?
  28 
  29   done
  30 
  31   echo "Number = $nr"
  32 
  33 
  34 exit 0

---

A reader sent in the following code snippet.
   1 while read LINE
   2 do
   3   echo $LINE
   4 done < `tail -f /var/log/messages`
He wished to write a script tracking changes to the system log file, /var/log/messages. Unfortunately, the above code block hangs and does nothing useful. Why? Fix this so it does work (hint: rather than redirecting the stdin of the loop, try a pipe).

---

Analyze Example A-11, and reorganize it in a simplified and more logical style. See how many of its variables can be eliminated and try to optimize the script to speed up its execution time.

Alter the script so that it accepts any ordinary ASCII text file as input for its initial "generation". The script will read the first $ROW*$COL characters, and set the occurrences of vowels as "living" cells. Hint: be sure to translate the spaces in the input file to underscore characters.