Cari di Shell Script 
    Shell Script Linux Reference Manual
Daftar Isi
(Sebelumnya) O. ExercisesO.2. Writing Scripts (Berikutnya)

O.1. Analyzing Scripts

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

#!/bin/bashMAX=10000  for((nr=1; nr<$MAX; nr++))  do let "t1 = nr % 5" if [ "$t1" -ne 3 ] then  continue fi let "t2 = nr % 7" if [ "$t2" -ne 4 ] then  continue fi let "t3 = nr % 9" if [ "$t3" -ne 5 ] then  continue fi  break   # What happens when you comment out this line? Why?  done  echo "Number = $nr" exit 0

---

Explain what the following script does. It is really just a parameterized command-line pipe.

#!/bin/bashDIRNAME=/usr/binFILETYPE="shell script" LOGFILE=logfilefile "$DIRNAME"/* | fgrep "$FILETYPE" | tee $LOGFILE | wc -lexit 0

---

Examine and explain the following script. For hints, you might refer to the listings for find and stat.

#!/bin/bash# Author:  Nathan Coulter# This code is released to the public domain.# The author gave permission to use this code snippet in the ABS Guide.find -maxdepth 1 -type f -printf '%f00'  | {   while read -d $'00' do  mv "$REPLY" "$(date -d "$(stat -c '%y' "$REPLY") " '+%Y%m%d%H%M%S'  )-$REPLY" done}# Warning: Test-drive this script in a "scratch" directory.# It will somehow affect all the files there.

---

A reader sent in the following code snippet.

while read LINEdo  echo $LINEdone < `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 the following "one-liner" (here split into two lines for clarity) contributed by Rory Winston:

export SUM=0; for f in $(find src -name "*.java");do export SUM=$(($SUM + $(wc -l $f | awk '{ print $1 }'))); done; echo $SUM

Hint: First, break the script up into bite-sizedsections. Then, carefully examine its use of double-parentheses arithmetic,the export command,the find command, thewc command, and awk.

---

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.


Copyright © 2000, by Mendel Cooper <[email protected]>
(Sebelumnya) O. ExercisesO.2. Writing Scripts (Berikutnya)