Previous Section  < Day Day Up >  Next Section

8.6. Looping Commands

Looping commands are used to execute a command or group of commands a set number of times or until a certain condition is met. The Bourne shell has three types of loops: for, while, and until.

8.6.1 The for Command

The for looping command is used to execute commands a finite number of times on a list of items. For example, you might use this loop to execute the same commands on a list of files or usernames. The for command is followed by a user-defined variable, the keyword in, and a list of words. The first time in the loop, the first word from the wordlist is assigned to the variable, and then shifted off the list. Once the word is assigned to the variable, the body of the loop is entered, and commands between the do and done keywords are executed. The next time around the loop, the second word is assigned to the variable, and so on. The body of the loop starts at the do keyword and ends at the done keyword. When all of the words in the list have been shifted off, the loop ends and program control continues after the done keyword.

FORMAT


for variable in word_list

do

   command(s)

done


Example 8.25.

(The Script)

   #!/bin/sh

   # Scriptname: forloop

1   for pal in Tom Dick Harry Joe

2   do

3       echo "Hi $pal"

4   done

5   echo "Out of loop"



(The Output)

$ forloop

Hi Tom

Hi Dick

Hi Harry

Hi Joe

Out of loop


EXPLANATION

  1. This for loop will iterate through the list of names, Tom, Dick, Harry, and Joe, shifting each one off (to the left and assigning its value to the user-defined variable, pal) after it is used. As soon as all of the words are shifted and the wordlist is empty, the loop ends and execution starts after the done keyword. The first time in the loop, the variable pal will be assigned the word Tom. The second time through the loop, pal will be assigned Dick, the next time pal will be assigned Harry, and the last time pal will be assigned Joe.

  2. The do keyword is required after the wordlist. If it is used on the same line, the list must be terminated with a semicolon. Example:

    
    for pal in Tom Dick Harry Joe; do
    
    

  3. This is the body of the loop. After Tom is assigned to the variable pal, the commands in the body of the loop (i.e., all commands between the do and done keywords) are executed.

  4. The done keyword ends the loop. Once the last word in the list (Joe) has been assigned and shifted off, the loop exits.

  5. Control resumes here when the loop exits.

Example 8.26.

(The Command Line)

1   $ cat mylist

    tom

    patty

    ann

    jake



(The Script)

    #!/bin/sh

    # Scriptname: mailer

2   for person in `cat mylist`

    do

3       mail $person < letter

        echo  $person was sent a letter.

4   done

5   echo "The letter has been sent."


EXPLANATION

  1. The contents of a file, called mylist, are displayed.

  2. Command substitution is performed and the contents of mylist becomes the wordlist. The first time in the loop, tom is assigned to the variable person, then it is shifted off to be replaced with patty, and so forth.

  3. In the body of the loop, each user is mailed a copy of a file called letter.

  4. The done keyword marks the end of this loop iteration.

  5. When all of the users in the list have been sent mail and the loop has exited, this line is executed.

Example 8.27.

(The Script)

    #!/bin/sh

    # Scriptname: backup

    # Purpose:

    # Create backup files and store them in a backup directory

1   dir=/home/jody/ellie/backupscripts



2   for file in memo[1-5]

    do

3       if [ -f $file ]

        then

             cp $file $dir/$file.bak

             echo "$file is backed up in $dir"

        fi

    done



(The Output)

memo1 is backed up in /home/jody/ellie/backupscripts

memo2 is backed up in /home/jody/ellie/backupscripts

memo3 is backed up in /home/jody/ellie/backupscripts

memo4 is backed up in /home/jody/ellie/backupscripts

memo5 is backed up in /home/jody/ellie/backupscripts


EXPLANATION

  1. The variable dir is assigned.

  2. The wordlist will consist of all files in the current working directory with names starting with memo and ending with a number between 1 and 5. Each filename will be assigned, one at time, to the variable file for each iteration of the loop.

  3. When the body of the loop is entered, the file will be tested to make sure it exists and is a real file. If so, it will be copied into the directory /home/jody/ellie/backupscripts with the .bak extension appended to its name.

8.6.2 The $* and $@ Variables in Wordlists

When expanded, the $* and $@ are the same unless enclosed in double quotes. $* evaluates to one string, whereas $@ evaluates to a list of separate words.

Example 8.28.

(The Script)

    #!/bin/sh

    # Scriptname: greet

1   for name in $*        # Same as for name in $@

2   do

        echo Hi $name

3   done

(The Command Line)

$ greet Dee Bert Lizzy Tommy

Hi Dee

Hi Bert

Hi Lizzy

Hi Tommy


EXPLANATION

  1. $* and $@ expand to a list of all the positional parameters, in this case, the arguments passed in from the command line: Dee, Bert, Lizzy, and Tommy. Each name in the list will be assigned, in turn, to the variable name in the for loop.

  2. The commands in the body of the loop are executed until the list is empty.

  3. The done keyword marks the end of the loop body.

Example 8.29.

(The Script)

    #!/bin/sh

    # Scriptname:permx

1   for file         # Empty wordlist

    do

2       if [ -f $file -a ! -x $file ]

        then

3           chmod +x $file

            echo $file now has execute permission

        fi

    done



(The Command Line)

4   $ permx *

    addon now has execute permission

    checkon now has execute permission

    doit now has execute permission


EXPLANATION

  1. If the for loop is not provided with a wordlist, it iterates through the positional parameters. This is the same as for file in $*.

  2. The filenames are coming in from the command line. The shell expands the asterisk (*) to all filenames in the current working directory. If the file is a plain file and does not have execute permission, line 3 is executed.

  3. Execute permission is added for each file being processed.

  4. At the command line, the asterisk will be evaluated by the shell as a wildcard and all files in the current directory will be replaced for the *. The files will be passed as arguments to the permx script.

8.6.3 The while Command

The while command evaluates the command immediately following it and, if its exit status is 0, the commands in the body of the loop (commands between do and done) are executed. When the done keyword is reached, control is returned to the top of the loop and the while command checks the exit status of the command again. Until the exit status of the command being evaluated by the while becomes nonzero, the loop continues. When the exit status reaches nonzero, program execution starts after the done keyword.

FORMAT


while command

do

    command(s)

done


Example 8.30.

(The Script)

     #!/bin/sh

     # Scriptname: num

1    num=0                         # Initialize num

2    while  [ $num -lt 10 ]        # Test num with test command

    do

          echo  -n $num

3         num=`expr  $num + 1`     # Increment num

    done

    echo "\nAfter loop exits, continue running here"



(The Output)

0123456789

After loop exits, continue running here


EXPLANATION

  1. This is the initialization step. The variable num is assigned 0.

  2. The while command is followed by the test (square brackets) command. If the value of num is less than 10, the body of the loop is entered.

  3. In the body of the loop, the value of num is incremented by 1. If the value of num never changes, the loop would iterate infinitely or until the process is killed.

Example 8.31.

(The Script)

     #!/bin/sh

     # Scriptname: quiz

1    echo "Who was the chief defense lawyer in the OJ case?"

     read answer

2    while [ "$answer" != "Johnny" ]

3    do

4        echo  "Wrong try again!"

         read answer

5    done

6    echo You got it!



(The Output)

$ quiz

Who was the chief defense lawyer in the OJ case? Marcia

Wrong try again!

Who was the chief defense lawyer in the OJ case?  I give up

Wrong try again!

Who was the chief defense lawyer in the OJ case?  Johnny

You got it!


EXPLANATION

  1. The echo command prompts the user, Who was the chief defense lawyer in the OJ case? The read command waits for input from the user. The input will be stored in the variable answer.

  2. The while loop is entered and the test command, the bracket, tests the expression. If the variable answer does not equal the string Johnny , the body of the loop is entered and commands between the do and done are executed.

  3. The do keyword is the start of the loop body.

  4. The user is asked to re-enter input.

  5. The done keyword marks the end of the loop body. Control is returned to the top of the while loop, and the expression is tested again. As long as $answer does not evaluate to Johnny, the loop will continue to iterate. When the user enters Johnny , the loop ends. Program control goes to line 6.

  6. When the body of the loop ends, control starts here.

Example 8.32.

(The Script)

    #!/bin/sh

    # Scriptname: sayit

    echo Type q to quit.

    go=start

1   while [ -n "$go" ]      # Make sure to double quote the variable

    do

2        echo -n I love you.

3        read word

4        if [ "$word" = q -o "$word" = Q ]

         then

             echo "I'll always love you!"

             go=

         fi

    done



(The Output)

$ sayit

Type q to quit.

I love you.     <- When user presses the Enter key, the program continues

I love you.

I love you.

I love you.

I love you.q

I'll always love you!

$


EXPLANATION

  1. The command after the while is executed and its exit status tested. The –n option to the test command tests for a non-null string. Because go initially has a value, the test is successful, producing a zero exit status. If the variable go is not enclosed in double quotes and the variable is null, the test command would complain:

    
    go: test: argument expected
    
    

  2. The loop is entered. The string I love you. is echoed to the screen.

  3. The read command waits for user input.

  4. The expression is tested. If the user enters a q or Q, the string I'll always love you! is displayed, and the variable go is set to null. When the while loop is re-entered, the test is unsuccessful because the variable is null. The loop terminates. Control goes to the line after the done statement. In this example, the script will terminate because there are no more lines to execute.

8.6.4 The until Command

The until command is used like the while command, but executes the loop statements only if the command after until fails; that is, if the command returns an exit status of nonzero. When the done keyword is reached, control is returned to the top of the loop and the until command checks the exit status of the command again. Until the exit status of the command being evaluated by until becomes 0, the loop continues. When the exit status reaches 0, the loop exits, and program execution starts after the done keyword.

FORMAT


until command

do

    command(s)

done


Example 8.33.

(The Script)

     #!/bin/sh

1    until who | grep linda

2    do

         sleep 5

3    done

     talk linda@dragonwings


EXPLANATION

  1. The until loop tests the exit status of the last command in the pipeline, grep. The who command lists who is logged on this machine and pipes its output to grep. The grep command will return a 0 exit status (success) only when it finds user linda.

  2. If user linda has not logged on, the body of the loop is entered and the program sleeps for five seconds.

  3. When linda logs on, the exit status of the grep command will be 0 and control will go to the statements following the done keyword.

Example 8.34.

(The Script)

     #!/bin/sh

     # Scriptname: hour

1    hour=1

2    until [ $hour  -gt 24 ]

     do



3      case "$hour" in

       [0-9] |1[0-1])   echo  "Good morning!"

             ;;

       12)  echo  "Lunch time."



             ;;

       1[3-7])   echo  "Siesta time."

             ;;

       *)   echo  "Good night."

             ;;

       esac

4      hour=`expr $hour + 1`

5   done



(The Output)

$ hour

Good morning!

Good morning!

    ...

Lunch time

Siesta time

    ...

Good night.

    ...


EXPLANATION

  1. The variable hour is initialized to 1.

  2. The test command tests if the hour is greater than 24. If the hour is not greater than 24, the body of the loop is entered. The until loop is entered if the command following it returns a nonzero exit status. Until the condition is true, the loop continues to iterate.

  3. The case command evaluates the hour variable and tests each of the case statements for a match.

  4. The hour variable is incremented before control returns to the top of the loop.

  5. The done command marks the end of the loop body.

8.6.5 Looping Control Commands

If some condition occurs, you may want to break out of a loop, return to the top of the loop, or provide a way to stop an infinite loop. The Bourne shell provides loop control commands to handle these kinds of situations.

The shift Command

The shift command shifts the parameter list to the left a specified number of times. The shift command without an argument shifts the parameter list once to the left. Once the list is shifted, the parameter is removed permanently. Often, the shift command is used in a while loop when iterating through a list of positional parameters.

FORMAT


shift [n]


Example 8.35.

(Without a loop)

(The Script)

     #!/bin/sh

1    set joe mary tom sam

2    shift

3    echo $*

4    set `date`

5    echo  $*

6    shift 5

7    echo  $*

8    shift 2



(The Output)

3    mary tom sam

5    Fri Sep 9 10:00:12 PDT 2004

7    2004

8    cannot shift


EXPLANATION

  1. The set command sets the positional parameters. $1 is assigned joe, $2 is assigned mary , $3 is assigned tom, and $4 is assigned sam. $* represents all of the parameters.

  2. The shift command shifts the positional parameters to the left; joe is shifted off.

  3. The parameter list is printed after the shift.

  4. The set command resets the positional parameters to the output of the UNIX date command.

  5. The new parameter list is printed.

  6. This time the list is shifted 5 times to the left.

  7. The new parameter list is printed.

  8. By attempting to shift more times than there are parameters, the shell sends a message to standard error.

Example 8.36.

(With a loop)

(The Script)

     #!/bin/sh

     # Name: doit

     # Purpose: shift through command-line arguments

     # Usage: doit [args]

1     while [  $# -gt  0 ]

      do

2        echo  $*

3        shift

4    done



(The Command Line)

$ doit a b c d e

a b c d e

b c d e

c d e

d e

e


EXPLANATION

  1. The while command tests the numeric expression. If the number of positional parameters ($#) is greater than 0, the body of the loop is entered. The positional parameters are coming from the command line as arguments. There are five.

  2. All positional parameters are printed.

  3. The parameter list is shifted once to the left.

  4. The body of the loop ends here; control returns to the top of the loop. Each time the loop is entered, the shift command causes the parameter list to be decreased by 1. After the first shift, $# (number of positional parameters) is four. When $# has been decreased to zero, the loop ends.

Example 8.37.

(The Script)

     #!/bin/sh

     # Scriptname: dater

     # Purpose: set positional parameters with the set command

     # and shift through the parameters.



1   set `date`

2   while [ $# -gt 0 ]

    do

3       echo $1

4       shift

    done

(The Output)

$ dater

Sat

Oct

16

12:12:13

PDT

2004


EXPLANATION

  1. The set command takes the output of the date command and assigns the output to positional parameters $1 through $6.

  2. The while command tests whether the number of positional parameters ($#) is greater than 0. If true, the body of the loop is entered.

  3. The echo command displays the value of $1, the first positional parameter.

  4. The shift command shifts the parameter list once to the left. Each time through the loop, the list is shifted until the list is empty. At that time, $# will be zero and the loop terminates.

The break Command

The built-in break command is used to force immediate exit from a loop, but not from a program. (To leave a program, the exit command is used.) After the break command is executed, control starts after the done keyword. The break command causes an exit from the innermost loop, so if you have nested loops, the break command takes a number as an argument, allowing you to break out of a specific outer loop. If you are nested in three loops, the outermost loop is loop number 3, the next nested loop is loop number 2, and the innermost nested loop is loop number 1. The break is useful for exiting from an infinite loop.

FORMAT


break [n]


Example 8.38.

    #!/bin/sh

1   while true; do

2       echo Are you ready to move on\?

        read answer

3       if [  "$answer"  =  Y -o "$answer" = y  ]

        then


EXPLANATION

  1. The true command is a UNIX command that always exits with 0 status. It is often used to start an infinite loop. It is okay to put the do statement on the same line as the while command, as long as a semicolon separates them. The body of the loop is entered.

  2. The user is asked for input. The user's input is assigned to the variable answer.

  3. If $answer evaluates to Y or y, control goes to line 4.

  4. The break command is executed, the loop is exited, and control goes to line 7. The line Here we are is printed. Until the user answers with a Y or y, the program will continue to ask for input. This could go on forever!

  5. If the test fails in line 3, the else commands are executed. When the body of the loop ends at the done keyword, control starts again at the top of the while at line 1.

  6. This is the end of the loop body.

  7. Control starts here after the break command is executed.

The continue Command

The continue command returns control to the top of the loop if some condition becomes true. All commands below the continue will be ignored. If nested within a number of loops, the continue command returns control to the innermost loop. If a number is given as its argument, control can then be started at the top of any loop. If you are nested in three loops, the outermost loop is loop number 3, the next nested loop is loop number 2, and the innermost nested loop is loop number 1.[3]

[3] If the continue command is given a number higher than the number of loops, the loop exits.

FORMAT


continue [n]


Example 8.39.

(The mailing List)

$ cat mail_list

ernie

john

richard

melanie

greg

robin





(The Script)

    #!/bin/sh

    # Scriptname: mailem

    # Purpose: To send a list



        else

4           mail $name < memo

        fi

5   done


EXPLANATION

  1. After command substitution, cat mail_list, the for loop will iterate through the list of names from the file called mail_list (i.e., ernie john richard melanie greg robin).

  2. If the name matches richard, the continue command is executed and control goes back to top of the loop where the loop expression is evalutated. Because richard has already been shifted off the list, the next user, melanie, will be assigned to the variable name. The string richard does not need to be quoted here because it is only one word. But, it is good practice to quote the string after the test's = operator because if the string consisted of more than one word, for example, richard jones, the test command would produce an error message:

    
    test: unknown operator richard
    
    

  3. The continue command returns control to the top of the loop, skipping any commands in the rest of the loop body.

  4. All users in the list, except richard, will be mailed a copy of the file memo.

  5. This is the end of the loop body.

8.6.6 Nested Loops and Loop Control

When using nested loops, the break and continue commands can be given a numeric, integer argument so that control can go from the inner loop to an outer loop.

Example 8.40.

(The Script)

     #!/bin/sh

     # Scriptname: months



(The Output)

$ months

Processing the month of Jan. Okay?

Processing the month of Feb. Okay? y

Process week 1 of Feb? y

Now processing week 1 of Feb.

Done processing...

Processing the month of Feb. Okay? y

Process week 2 of Feb? y

Now processing week 2 of Feb.

Done processing...

Processing the month of Feb. Okay? n

Processing the month of Mar. Okay? n

Processing the month of Apr. Okay? n

Processing the month of May. Okay? n


EXPLANATION

  1. The outer for loop is started. The first time in the loop, Jan is assigned to month.

  2. The inner for loop starts. The first time in this loop, 1 is assigned to week. The inner loop iterates completely before going back to the outer loop.

  3. If the user enters either an n or presses Enter, line 4 is executed.

  4. The continue command with an argument of 2 starts control at the top of the second outermost loop. The continue without an argument returns control to the top of the innermost loop.

  5. Control is returned to the innermost for loop.

  6. This done terminates the innermost loop.

  7. This done terminates the outermost loop.

8.6.7 I/O Redirection and Subshells

Input can be piped or redirected to a loop from a file. Output can also be piped or redirected to a file from a loop. The shell starts a subshell to handle I/O redirection and pipes. Any variables defined within the loop will not be known to the rest of the script when the loop terminates.

Redirecting the Output of a Loop to a File

See Example 8.41 for a demonstration of how to redirect the output of a loop to a file.

Example 8.41.

(The Command Line)

1    $ cat memo

     abc

     def

     ghi



(The Script)

     #!/bin/sh

     # Program name: numberit

     # Put line numbers on all lines of memo

2    if [ $# -lt  1 ]

     then

3        echo  "Usage: $0 filename " >&2

         exit 1

     fi

4    count=1                     # Initialize count

5    cat $1 | while read line    # Input is coming from file on command line

     do

6         [ $count -eq 1 ] && echo "Processing file $1..." > /dev/tty

7         echo $count $line

8         count=`expr $count + 1`

9    done > tmp$$                   # Output is going to a temporary file

10   mv tmp$$ $1



(The Command Line)

11   $ numberit memo

     Processing file memo...



12   $ cat memo

     1 abc

     2 def

     3 ghi


EXPLANATION

  1. The contents of file memo are displayed.

  2. If the user did not provide a command-line argument when running this script, the number of arguments ($#) will be less than 1 and the error message appears.

  3. The usage message is sent to stderr (>&2) if the number of arguments is less than 1.

  4. The count variable is assigned the value 1.

  5. The UNIX cat command displays the contents of the filename stored in $1, and the output is piped to the while loop. The read command is assigned the first line of the file the first time in the loop, the second line of the file the next time through the loop, and so forth. The read command returns a 0 exit status if it is successful in reading input and 1 if it fails.

  6. If the value of count is 1, the echo command is executed and its output is sent to /dev/tty , the screen.

  7. The echo command prints the value of count, followed by the line in the file.

  8. The count is incremented by 1.

  9. The output of this entire loop, each line of the file in $1, is redirected to the file tmp$$, with the exception of the first line of the file, which is redirected to the terminal, /dev/tty.[a]

    [a] $$ expands to the PID number of the current shell. By appending this number to the filename, the filename is made unique.

  10. The tmp file is renamed to the filename assigned to $1.

  11. The program is executed. The file to be processed is called memo.

  12. The file memo is displayed after the script has finished, demonstrating that line numbers have been prepended to each line.

Example 8.42.

(The Input File)

$ cat testing

apples

pears

peaches



(The Script)

     #!/bin/sh

     # This program demonstrates the scope of variables when

     # assigned within loops where the looping command uses

     # redirection. A subshell is started when the loop uses

     # redirection, making all variables created within the loop

     # local to the shell where the loop is being executed.

1    while read line

     do

2        echo $line    # This line will be redirected to outfile

3        name=JOE

4    done < testing > outfile  # Redirection of input and output

5    echo Hi there $name



(The Output)

5    Hi there


EXPLANATION

  1. If the exit status of the read command is successful, the body of the while loop is entered. The read command is getting input from the file testing, named after the done on line 4. Each time through the loop, the read command reads another line from the file testing.

  2. The value of line will be redirected to outfile in line 4.

  3. The variable name is assigned JOE. Because redirection is utilized in this loop, the variable is local to the loop.

  4. The done keyword consists of the redirection of input from the file testing, and the redirection of output to the file outfile. All output from this loop will go to outfile.

  5. When out of the loop, name is undefined. It was local to the while loop and known only within the body of that loop. Because the variable name has no value, only the string Hi there is displayed.

Piping the Output of a Loop to a UNIX Command

Output can be either piped to another command(s) or redirected to a file.

Example 8.43.

(The Script)

     #!/bin/sh

1    for i in 7 9 2 3 4  5

2    do

         echo  $i

3    done | sort –n



(The Output)

2

3

4

5

7

9


EXPLANATION

  1. The for loop iterates through a list of unsorted numbers.

  2. In the body of the loop, the numbers are printed. This output will be piped into the UNIX sort command, a numerical sort.

  3. The pipe is created after the done keyword. The loop is run in a subshell.

8.6.8 Running Loops in the Background

Loops can be executed to run in the background. The program can continue without waiting for the loop to finish processing.

Example 8.44.

(The Script)

     #!/bin/sh

1    for person in bob jim joe sam

     do

2        mail $person < memo

3    done &


EXPLANATION

  1. The for loop shifts through each of the names in the wordlist: bob, jim, joe, and sam. Each of the names is assigned to the variable person, in turn.

  2. In the body of the loop, each person is sent the contents of the memo file.

  3. The ampersand at the end of the done keyword causes the loop to be executed in the background. The program will continue to run while the loop is executing.

8.6.9 The exec Command and Loops

The exec command can be used to open or close standard input or output without creating a subshell. Therefore, when starting a loop, any variables created within the body of the loop will remain when the loop completes. When using redirection in loops, any variables created within the loop are lost.

The exec command is often used to open files for reading and writing, either by name or by file descriptor number. Recall that file descriptors 0, 1, and 2 are reserved for standard input, output, and error. If a file is opened, it will receive the next available file descriptor. For example, if file descriptor 3 is the next free descriptor, the new file will be assigned file descriptor 3.

Example 8.45.

(The File)

1    $ cat tmp

     apples

     pears

     bananas

     pleaches

     plums



(The Script)

     #!/bin/sh

     # Scriptname: speller

     # Purpose: Check and fix spelling errors in a file

2    exec < tmp                   # Opens the tmp file

3    while read line              # Read from the tmp file

     do

4        echo $line

5        echo  –n  "Is this word correct? [Y/N] "

6        read answer < /dev/tty   # Read from the terminal

7        case  "$answer" in

8       [Yy]*)

9            continue;;

        *)

             echo  "What is the correct spelling? "

10           read word < /dev/tty

11           sed  "s/$line/$word/g" tmp > error

12           mv error tmp

13           echo $line has been changed to $word.

        esac

14   done


EXPLANATION

  1. The contents of the tmp file are displayed.

  2. The exec command changes standard input (file descriptor 0) so that instead of input coming from the keyboard, it is coming from the tmp file.

  3. The while loop starts. The read command gets a line of input from the tmp file.

  4. The value stored in the line variable is printed.

  5. The user is asked if the word is correct.

  6. The read gets the user's response from the terminal, /dev/tty . If the input is not redirected directly from the terminal, it will continue to be read from the file tmp, still opened for reading.

  7. The case command evalutates the user's answer.

  8. If the variable answer evaluates to a string starting with a Y or y, the continue statement on the next line will be executed.

  9. The continue statement causes the program to go to the beginning of the while loop on line 3.

  10. The user is again asked for input (the correct spelling of the word). The input is redirected from the terminal, /dev/tty.

  11. The sed command will replace the value of line with the value of word wherever it occurs in the tmp file, and send the output to the error file.

  12. The error file will be renamed tmp, thus overwriting the old contents of tmp with the contents of the error file.

  13. This line is displayed to indicate that the change has been made.

  14. The done keyword marks the end of the loop body.

8.6.10 IFS and Loops

The shell's internal field separator (IFS) evaluates to spaces, tabs, and the newline character. It is used as a word (token) separator for commands that parse lists of words, such as read, set, and for. It can be reset by the user if a different separator will be used in a list. Before changing its value, it is a good idea to save the original value of the IFS in another variable. Then it is easy to return to its default value, if needed.

Example 8.46.

(The Script )

     #/bin/sh

     # Scriptname: runit

     # IFS is the internal field separator and defaults to

     # spaces, tabs, and newlines.

     # In this script it is changed to a colon.

1    names=Tom:Dick:Harry:John

2    OLDIFS="$IFS"     # Save the original value of IFS

3    IFS=":"

4    for persons in $names

     do

5        echo  Hi $persons

     done

6    IFS="$OLDIFS"             # Reset the IFS to old value

7    set Jill Jane Jolene      # Set positional parameters

8    for girl in $*

     do

9        echo Howdy $girl

     done



(The Output)

5    Hi Tom

     Hi Dick

     Hi Harry

     Hi John

9    Howdy Jill

     Howdy Jane

     Howdy Jolene


EXPLANATION

  1. The names variable is assigned the string Tom:Dick:Harry:John. Each of the words is separated by a colon.

  2. The value of IFS, whitespace, is assigned to another variable, OLDIFS. Because the value of the IFS is whitespace, it must be quoted to preserve it.

  3. The IFS is assigned a colon. Now the colon is used to separate words.

  4. After variable substitution, the for loop will iterate through each of the names, using the colon as the internal field separator between the words.

  5. Each of the names in the wordlist are displayed.

  6. The IFS is reassigned its original value stored in OLDIFS.

  7. The positional parameters are set. $1 is assigned Jill, $2 is assigned Jane, and $3 is assigned Jolene.

  8. $* evaluates to all the positional parameters, Jill, Jane, and Jolene. The for loop assigns each of the names to the girl variable, in turn, through each iteration of the loop.

  9. Each of the names in the parameter list is displayed.

    Previous Section  < Day Day Up >  Next Section