12.6. Looping Commands
The 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 Korn shell has four types of loops: for, while, until, and select.
12.6.1 The for Command
The for looping command is used to execute commands for each member of a set of arguments. 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 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 wordlist
do
command(s)
done
Example 12.29.
(The Script)
1 for pal in Tom Dick Harry Joe
2 do
3 print "Hi $pal"
4 done
5 print "Out of loop"
(The Output)
Hi Tom
Hi Dick
Hi Harry
Hi Joe
Out of loop
EXPLANATION
This for loop will iterate through the list of names, Tom, Dick, Harry, and Joe, shifting each one off (to the left) after it is assigned to the variable pal. 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 word following the for command, pal, is a variable that will be assigned the value after the in keyword, one at a time, for each iteration of the loop. 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. The do keyword is required after the wordlist. If it is used on the same line, the list must be terminated with a semicolon. For example:
for pal in Tom Dick Harry Joe; do
This is the body of the loop. After Tom is assigned to the variable pal, the commands in the body of the loop, that is, all commands between the do and the done keywords, are executed. The done keyword ends the loop. If there are no words left to be processed in the wordlist on line 1, the loop exits, and execution starts at line 5. This line is executed when the loop terminates.
Example 12.30.
(The Command Line)
1 $ cat mylist
tom
patty
ann
jake
(The Script)
2 for person in $(< mylist) #same as for person in `cat mylist`
do
3 mail $person < letter
print $person was sent a letter.
4 done
5 print "The letter has been sent."
EXPLANATION
The contents of a file, mylist, are displayed. Command substitution is performed and the contents of mylist become the wordlist. The first time in the loop, tom is assigned to the variable person, and then shifted off, to be replaced with patty, and so on. In the body of the loop, each user is mailed a copy of a file called letter. The done keyword marks the end of this loop iteration. When all of the users in the list have been sent mail, the loop will exit, and this line will be executed.
Example 12.31.
1 for file in *.c
2 do
if [[ -f $file ]] ; then
cc $file -o ${file%.c}
fi
done
EXPLANATION
The wordlist will consist of all files in the current working directory ending with the extension .c (C source files). Each filename will be assigned to variable file, in turn, for each iteration of the loop. 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 compiled. ${file%.c} expands to the filename without its extension.
12.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 12.32.
(The Script)
#!/bin/ksh
1 for name in $* # or 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
$* 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 name variable in the for loop. The commands in the body of the loop are executed until the list is empty. The done keyword marks the end of the loop body.
12.6.3 The while Command
The while 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. If the exit status never becomes nonzero, the loop goes around and around infinitely. (Of course, pressing Ctrl-C or Ctrl-\ will stop the looping.)
FORMAT
while command
do
command(s)
done
Example 12.33.
(The Script)
1 num=0 # Initialize num
2 while (( num < 10 )) # Test num with the let
do
print -n $num
3 (( num=num + 1 )) # Increment num
done
print "\nAfter loop exits, continue running here"
(The Output)
0123456789
After loop exits, continue running here
EXPLANATION
This is the initialization step. The variable num is assigned 0. The while command is followed by the let command. If the value of num is less than 10, the body of the loop is entered. In the body of the loop, the value of num is incremented by one. If the value of num was never changed, the loop would iterate infinitely or until the process was killed.
Example 12.34.
(The Script)
#!/bin/ksh
# Scriptname: quiz
1 read answer?"Who was the U.S. President in 1992? "
2 while [[ $answer != "Bush" ]]
3 do
print "Wrong try again!"
4 read answer
5 done
6 print Good guess!
(The Output)
$ quiz
Who was the U.S. President in 1992? George
Wrong try again!
Who was the U.S. President in 1992? I give up
Wrong try again!
Who was the U.S. President in 1992? Bush
Good guess!
EXPLANATION
The read command prints the string after the question mark (?), Who was the U.S. President in 1992?, and waits for input from the user. The input will be stored in the variable answer. The while loop is entered and the test command, [[, evaluates the expression. If the variable answer does not equal the string Bush, the body of the loop is entered and commands between the do and done are executed. The do keyword is the start of the loop body. The user is asked to re-enter input. 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 Bush, the loop will continue to iterate. When the user's input is Bush, the loop ends. Program control goes to line 6.
Example 12.35.
(The Script)
1 go=1
print Type q to quit.
2 while let go or (( go ))
do
print I love you.
read word
3 if [[ $word = [qQ]* ]]
then
print "I'll always love you"
4 go=0
fi
5 done
(The Output)
$ sayit
Type q to quit.
I love you.
I love you.
I love you.
I love you.
I love you.
q
I'll always love you
$
EXPLANATION
The variable go is assigned 1. The loop is entered. The let command tests the expression. The expression evaluates to one. The program goes into the body of the while loop and executes commands from the do keyword to the done keyword. If the user enters a q or Q as input to the variable word, the commands between then and fi are executed. Anything else will cause I love you. to be displayed. The variable go is assigned 0. When program control starts at the top of the while loop, the expression will be tested. Because the expression evaluates to false, the loop exits and the script starts execution after the done keyword on line 5. The done marks the end of the body of the loop.
12.6.4 The until Command
The until command is used like the while command, but evaluates the exit status in the opposite way. The until evaluates the command immediately following it, and if its exit status is not 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 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, program execution starts after the done keyword.
FORMAT
until command
do
command(s)
done
Example 12.36.
#!/bin/ksh
1 until who | grep linda
2 do
sleep 5
3 done
talk linda@dragonwings
EXPLANATION
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 0 exit status (success) only when it finds user linda. If user linda has not logged in, the body of the loop is entered and the program sleeps for 5 seconds. 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 12.37.
#!/bin/ksh
1 hour=0
2 until (( hour > 23 ))
do
3 case "$hour" in
[0-9]|1[0-1]) print "Good morning!"
;;
12) print "Lunch time"
;;
1[3-7]) print "Siesta time"
;;
*) print "Good night"
;;
esac
4 (( hour+=1 ))
5 done
EXPLANATION
The hour variable is assigned 0. The variable must be initialized before being used in the until loop. The until command is followed by the let command. If the hour is not greater than 23, that is, the exit status is nonzero, the loop body is entered. The case command matches the value of the hour variable against one of the hour values, or matches the default, executing the command that applies. The hour is incremented by 1; otherwise, the hour will never become greater than 23 and the loop will never exit. Control is returned to the until command and the hour is evaluated again. The done keyword marks the end of the loop. When the hour is greater than 23, control will go to the line under the done, if there is one; otherwise, the program is exited.
12.6.5 The select Command and Menus
The here document is an easy method for creating menus, but the Korn shell introduces a new loop, called the select loop, which is used primarily for creating menus. A menu of numerically listed items is displayed to standard error. The PS3 prompt is used to prompt the user for input; by default, PS3 is #?. After the PS3 prompt is displayed, the shell waits for user input. The input should be one of the numbers in the menu list. The input is stored in the special Korn shell REPLY variable. The number in the REPLY variable is associated with the string to the right of the parentheses in the list of selections.
The case command is used with the select command to allow the user to make a selection from the menu and, based on that selection, execute commands. The LINES and COLUMNS variables can be used to determine the layout of the menu items displayed on the terminal. The output is displayed to standard error, each item preceded by a number and closing parenthesis, and the PS3 prompt is displayed at the bottom of the menu. Because the select command is a looping command, it is important to remember to use either the break command to get out of the loop, or the exit command to exit the script.
FORMAT
select var in wordlist
do
command(s)
done
Example 12.38.
(The Script)
#!/bin/ksh
# Program name: goodboys
1 PS3="Please choose one of the three boys : "
2 select choice in tom dan guy
3 do
4 case $choice in
tom)
print Tom is a cool dude!
5 break;; # break out of the select loop
6 dan | guy )
print Dan and Guy are both sweethearts.
break;;
*)
7 print " $REPLY is not one of your choices" 1>&2
print "Try again."
;;
8 esac
9 done
(The Command Line)
$ goodboys
1) tom
2) dan
3) guy
Please choose one of the three boys : 2
Dan and Guy are both sweethearts.
$ goodboys
1) tom
2) dan
3) guy
Please choose one of the three boys : 4
4 is not one of your choices
Try again.
Please choose one of the three boys : 1
Tom is a cool dude!
$
EXPLANATION
The PS3 variable is assigned the prompt that will appear below the list of menu selections. After the prompt is displayed, the program waits for user input. The input is stored in the built-in variable called REPLY. The select command is followed by the variable choice. This syntax is similar to that of the for loop. The variable choice is assigned, in turn, each of the items in the list that follows it; in this case, tom, dan, and guy. It is this wordlist that will be displayed in the menu, preceded by a number and a right parenthesis. The do keyword indicates the start of the body of the loop. The first command in the body of the select loop is the case command. The case command is normally used with the select loop. The value in the REPLY variable is associated with one of the choices: 1 is associated with tom, 2 is associated with dan, and 3 is associated with guy. If tom is the choice, after printing the string Tom is a cool dude!, the break command causes the select loop to be exited. Program control starts after the done keyword. If either menu item, 2 (dan) or 3 (tom), is selected, the REPLY variable contains the user's selection. If the selection is not 1, 2, or 3, an error message is sent to standard error. The user is asked to try again and control starts at the beginning of the select loop. The end of the case command. The end of the select loop.
Example 12.39.
(The Script)
#!/bin/ksh
# Program name: ttype
# Purpose: set the terminal type
# Author: Andy Admin
1 COLUMNS=60
2 LINES=1
3 PS3="Please enter the terminal type: "
4 select choice in wyse50 vt200 vt100 sun
do
5 case $REPLY in
1)
6 export TERM=$choice
print "TERM=$choice"
break;; # break out of the select loop
2 | 3 )
export TERM=$choice
print "TERM=$choice"
break;;
4)
export TERM=$choice
print "TERM=$choice"
break;;
*)
7 print "$REPLY is not a valid choice. Try again" 1>&2
;;
esac
8 done
(The Command Line)
$ ttype
1) wyse50 2) vt200 3) vt100 4) sun
Please enter the terminal type : 4
TERM=sun
$ ttype
1) wyse50 2) vt200 3) vt100 4) sun
Please enter the terminal type : 3
TERM=vt100
$ ttype
1) wyse50 2) vt200 3) vt100 4) sun
Please enter the terminal type : 7
7 is not a valid choice. Try again.
Please enter the terminal type: 2
TERM=vt200
EXPLANATION
The COLUMNS variable is set to the width of the terminal display in columns for menus created with the select loop. The default is 80. The LINES variable controls the vertical display of the select menu on the terminal. The default is 24 lines. By changing the LINES value to 1, the menu items will be printed on one line, instead of vertically as in the last example. The PS3 prompt is set and will appear under the menu choices. The select loop will print a menu with four selections: wyse50, vt200, vt100, and sun. The variable choice will be assigned one of these values based on the user's response held in the REPLY variable. If REPLY is 1, wyse50 is assigned to choice; if REPLY is 2, vt200 is assigned to choice; if REPLY is 3, vt100 is assigned to choice; and if REPLY is 4, sun is assigned to choice. The REPLY variable evaluates to the user's input selection. The terminal type is assigned, exported, and printed. If the user does not enter a number between 1 and 4, he or she will be prompted again. Note that the menu does not appear, just the PS3 prompt. To make the menu reappear, set the REPLY variable to null. Type above line 8: REPLY = The end of the select loop.
12.6.6 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 Korn shell provides loop control commands to control loops.
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 while loops when iterating through a list of positional parameters.
FORMAT
shift [n]
Example 12.40.
(Without a Loop)
(The Script)
#!/bin/ksh
# Scriptname: doit0
1 set joe mary tom sam
2 shift
3 print $*
4 set $(date)
5 print $*
6 shift 5
7 print $*
8 shift 2
(The Output)
$ doit0
3 mary tom sam
5 Sun Sep 9 10:00:12 PDT 2004
7 2004
8 ksh: shift: bad number
EXPLANATION
The set command sets the positional parameters. $1 is assigned joe, $2 is assigned mary, $3 is assigned tom, and $4 is assigned sam. The shift command shifts the positional parameters to the left; joe is shifted off. The parameter list is printed after the shift. $* represents all of the parameters. The set command resets the positional parameters to the output of the UNIX date command. The new parameter list is printed. This time the list is shifted five times to the left. The new parameter list is printed. By attempting to shift more times than there are parameters, the shell sends a message to standard error.
Example 12.41.
(With a Loop)
(The Script)
#!/bin/ksh
# Usage: doit [args]
1 while (( $# > 0 ))
do
2 print $*
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
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. All the positional parameters are printed. The parameter list is shifted once to the left. The body of the loop ends here; control returns to the top of the loop. The parameter list has decreased by one. After the first shift, $# is four. When $# has been decreased to 0, the loop ends.
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 exit out of any number of outer loops. The break is useful for exiting from an infinite loop.
FORMAT
break [n]
Example 12.42.
1 while true; do
2 read answer? Are you ready to move on\?
3 if [[ $answer = [Yy]* ]]; then
EXPLANATION
The true command is a UNIX command, and an alias for the colon command in the Korn shell. It always exits with 0 status and is often used to start an infinite loop. (The null command (:) can be used to do the same thing.) The body of the loop is entered. The user is asked for input. The user's input is assigned to the variable answer. If answer evaluates to Y , y , Yes, Yup, or Ya (anything beginning with Y or y), the break command is executed and control goes to line 6. The line Here we are is printed. Until the user answers something that starts with a Y or y , the program will continue to ask for input. This could go on forever! 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. The end of the loop body. Control starts here after the break command is executed.
The continue Command
The continue command starts back at the top of the loop if some condition becomes true. All commands below the continue will be ignored. The continue command returns control to the top of the innermost loop; if nested within a number of loops, the continue command may take a number as its argument. Control can be started at the top of any number of outer loops.
FORMAT
continue [n]
Example 12.43.
(The Mailing List)
$ cat mail_list
ernie
john
richard
melanie
greg
robin
(The Script)
# Scriptname: mailtomaillist
#!/bin/ksh
4 mail $name < memo
fi
5 done
EXPLANATION
The for loop will iterate through a list of names stored in a file called mail_list. Each time a name from the list is assigned to the variable name, it is shifted off the list and replaced by the next name on the list. The name matches richard; the continue command is executed. Because richard has already been shifted off, the next user, melanie, is assigned to the variable name. The continue command returns control to the top of the loop, skipping any commands in the rest of the loop body. All users in the list, except richard, will be mailed a copy of the file memo. The end of the loop body.
12.6.7 Nested Loops and Loop Control
If using nested loops, the break and continue commands let you control which loop to terminate.
Example 12.44.
(The Script)
#!/bin/ksh
8 done
9 print Out of loop
EXPLANATION
The true command always returns an exit status of zero. The loop is designed to go forever unless you use loop control commands. The for loop will loop through each of the names in the list. If the user variable begins with a D or d, the continue command causes control to go to the top of the while loop. Without an argument, the continue command would start control at the top of the for loop. The argument 2 tells the shell to go to the top of the second enclosing loop and restart execution there. The while loop is nested. The true command always exits with zero status. The loop will go forever. The break command terminates the outermost while loop. Execution starts at line 9. The done keyword marks the end of the innermost while loop. This done keyword marks the end of the for loop. This done keyword marks the end of outermost while loop.
12.6.8 I/O Redirection and Loops
The Korn shell allows you to use redirection and pipes in loops. Unlike the Bourne shell, the loop runs in this shell, not a subshell. Variables set within the loop will still be set when the loop exits.
Redirecting the Output of a Loop to a File
Instead of sending the output of a loop to the screen, it can be redirected to a file or a pipe. See Example 12.45.
Example 12.45.
(The Command Line)
1 $ cat memo
abc
def
ghi
------------------------------------------------------------------
(The Script)
#!/bin/ksh
# Program name: numberit
# Put line numbers on all lines of memo
2 if (( $# < 1 ))
then
print "Usage: $0 filename " >&2
exit 1
fi
3 integer count=1 # Initialize count
4 cat $1 | while read line # Input is coming from memo
do
5 (( count == 1 )) && print "Processing file $1..." > /dev/tty
6 print $count $line
7 (( count+=1 ))
8 done > tmp$$ # Output is going to a temporary file
9 mv tmp$$ $1
(The Command Line)
10 $ numberit memo
Processing file memo...
11 $ cat memo
1 abc
2 def
3 ghi
EXPLANATION
The contents of file memo are displayed. If the number of arguments is less than one, a usage message is sent to standard error, the screen. The count variable is declared an integer and is assigned the value 1. 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 output of this print statement is sent to /dev/tty , the screen. If not explicitly redirected to /dev/tty , the output will be redirected to tmp$$ on line 8. The print function prints the value of count, followed by the line in the file. The count variable is incremented by 1. The output of this entire loop, with the exception of line 3, is redirected to the file tmp$$ (where $$ evaluates to the PID of this process). The tmp file is given a unique name by appending the PID of this process to its name. The tmp file is renamed to the name of the file that was assigned to $1. The program is executed. The file to be processed is called memo. The file is displayed with line numbers.
Piping the Output of a Loop to a UNIX Command
The output of a loop can be redirected from the screen to a pipe. See Example 12.46.
Example 12.46.
(The Script)
1 for i in 7 9 2 3 4 5
2 do
print $i
3 done | sort –n
(The Output)
2
3
4
5
7
9
EXPLANATION
The for loop iterates through a list of unsorted numbers. In the body of the loop, the numbers are printed. This output will be piped into the UNIX sort command. The pipe is created after the done keyword.
12.6.9 Running Loops in the Background
If the loop is going to take a while to process, it can be run as a background job so that the rest of the program can continue.
Example 12.47.
1 for person in bob jim joe sam
do
2 mail $person < memo
3 done &
EXPLANATION
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. In the body of the loop, each person is sent the contents of the file memo. 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.
12.6.10 The exec Command and Loops
The exec command can be used to close standard input or output without creating a subshell.
Example 12.48.
(The File)
1 cat tmp
apples
pears
bananas
peaches
plums
-----------------------------------------------------------
(The Script)
#!/bin/ksh
# 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 print $line
5 print –n "Is this word correct? [Y/N] "
6 read answer < /dev/tty # Read from the terminal
case $answer in
[Yy]*)
continue
;;
*)
print "New word? "
7 read word < /dev/tty
sed "s/$line/$word/" tmp > error
mv error tmp
8 print $word has been changed.
;;
esac
done
EXPLANATION
The contents of the tmp file are displayed. 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. The while loop starts. The read command gets a line of input from the tmp file. The value stored in the line variable is printed to the screen. The user is asked if the word is correct. The read command 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 input. The user is again asked for input, and the input is redirected from the terminal, /dev/tty. The new word is displayed.
12.6.11 The IFS and Loops
The IFS, the shell's internal field separator, 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, for, and select. It can be reset by the user if a different separator will be used in a list. It is a good idea to save the original value of the IFS in another variable before changing it. Then it is easy to return to its default value.
Example 12.49.
(The Script)
#!/bin/ksh
# 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 print 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
print Howdy $girl
done
(The Output)
$ runit
Hi Tom
Hi Dick
Hi Harry
Hi John
Howdy Jill
Howdy Jane
Howdy Jolene
EXPLANATION
The names variable is set to the string Tom:Dick:Harry:John. Each of the words is separated by a colon. The value of IFS is assigned to another variable, OLDIFS. Because the value of the IFS is whitespace, it must be quoted to preserve the whitespace. The IFS is assigned a colon. Now the colon is used to separate words. After variable substitution, the for loop will iterate through each of the names using the colon as the internal field separator between the words. Each of the names in the wordlist is displayed. IFS is reassigned its original values, stored in OLDIFS. The positional parameters are set. $1 is assigned Jill, $2 is assigned Jane, and $3 is assigned Jolene. $* 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.
|