Appendix M. Exercises
Examine the following script. Run it, then explain what itdoes. Annotate the script and rewrite it in a more compact andelegant 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 happens when you comment out this line? Why? 28 29 done 30 31 echo "Number = $nr" 32 33 34 exit 0
---
Explain what the following script does. It is really justa parameterized command-line pipe.
1 #!/bin/bash 2 3 DIRNAME=/usr/bin 4 FILETYPE="shell script" 5 LOGFILE=logfile 6 7 file "$DIRNAME"/* | fgrep "$FILETYPE" | tee $LOGFILE | wc -l 8 9 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 logfile, /var/log/messages. Unfortunately,the above code block hangs and does nothinguseful. Why? Fix this so it does work. (Hint:rather than redirecting thestdinof the loop, try a pipe.)
---
Analyze Example A-10, and reorganize it in asimplified and more logical style. See how many of the variablescan be eliminated, and try to optimize the script to speed upits execution time.
Alter the script so that it accepts any ordinary ASCIItext file as input for its initial "generation". Thescript will read the first $ROW*$COLcharacters, and set the occurrences of vowels as"living"cells. Hint: be sure to translate thespaces in the input file to underscore characters.