Section 8.9. Control Structures


[Page 314 (continued)]

8.9. Control Structures

The C shell supports a wide range of control structures that make it suitable as a high-level programming tool. Shell programs are usually stored in scripts and are commonly used to automate maintenance and installation tasks.

Several of the control structures require several lines to be entered. If such a control structure is entered from the keyboard, the shell prompts you with a ? for each additional line until the control structure is ended, at which point it executes.

There now follows a description of each control structure, in alphabetical order. I made the C shell examples correspond closely to the Bash examples so that you can compare and contrast the two shells.

8.9.1. foreach .. end

The foreach command allows a list of commands to be repeatedly executed, each time using a different value for a named variable. Figure 8-22 gives the syntax.


[Page 315]

Figure 8-22. Description of the foreach shell command.


foreach name ( wordList )
 commandList
end

The foreach command iterates the value of name through each item in wordList, executing the list of commands commandList after each assignment. A break command causes the loop to immediately end, and a continue command causes the loop to jump immediately to the next iteration.


Here's an example of a script that uses a foreach control structure:

% cat foreach.csh         ...list the script. # foreach color (red yellow green blue)         # four colors  echo one color is $color end % tcsh foreach.csh                 ...execute the script. one color is red one color is yellow one color is green one color is blue % _\ 


8.9.2. goto

The goto command allows you to jump unconditionally to a named label. To declare a label, simply start a line with the name of the label followed immediately by a colon. Figure 8-23 gives the syntax of a goto command.

Figure 8-23. Description of the goto shell command.

goto name

where later there exists a label of the form:

name:

When a goto statement is encountered, control is transferred to the line after the label location. The label may precede or follow the goto statement, even if the command is entered from the keyboard.


Use goto sparingly to avoid nasty spaghettilike code (even if you like spaghetti). Here's an example of a simple goto:

% cat goto.csh                ...list the script. # 
[Page 316]
echo gotta jump goto endOfScript # jump echo I will never echo this endOfScript: # label echo the end % tcsh goto.csh ...execute the script. gotta jump the end % _


8.9.3. if .. then .. else .. endif

There are two forms of if command. Figure 8-24 gives the syntax of the first form, which supports a simple one-way branch.

Figure 8-24. Description of the if shell command in its simple form.

if ( expr ) command

This form of the if command evaluates expr, and if it is true (nonzero), executes command.


Here is an example of this form of if:

% if (5 > 3) echo five is greater than 3 five is greater than three % _ 


The second form of the if command (Figure 8-25) supports alternative branching.

Figure 8-25. Description of the if shell command with else clauses.


if ( expr1 )then
  list1
else if ( expr2 ) then
  list2
else
  list3
endif

The else and else if portions of this command are optional, but the terminating endif is not. expr1 is executed. If expr1 is true, the commands in list1 are executed and the if command is done. If expr1 is false and there are one or more else if components, then a true expression following an else if causes the commands following the associated then to be executed and the if command to finish. If no true expressions are found and there is an else component, the commands following the else are executed.



[Page 317]

Here's an example of the second form of if:

% cat if.csh                  ...list the script. # echo -n 'enter a number: '    # prompt user. set number = $<               # read a line of input. if ($number < 0) then  echo negative else if ($number == 0) then  echo zero else  echo positive endif % tcsh if.csh                 ...execute the script. enter a number: -1 negative % _ 


8.9.4. onintr

The onintr command (Figure 8-26) allows you to specify a label that should be jumped to when the shell receives a SIGINT signal. This signal is typically generated by a Control-C from the keyboard, and is described in more detail in Chapter 12, "Systems Programming."

Figure 8-26. Description of the onintr shell command.

onintr [- | label]

The onintr command instructs the shell to jump to label when SIGINT is received. If the option is used, SIGINTs are ignored. If no options are supplied, it restores the shell's original SIGINT handler.


Here's an example:

% cat onintr.csh            ...list the script. # onintr controlC             # set Control-C trap. while (1)  echo infinite loop  sleep 2 end controlC: echo control C detected % tcsh onintr.csh           ...execute the script. infinite loop infinite loop ^C                          ...press Control-C. control C detected % _ 



[Page 318]

8.9.5. repeat

The repeat command allows you to execute a single command a specified number of times. Figure 8-27 gives the syntax.

Figure 8-27. Description of the repeat shell command.

repeat expr command

The repeat command evaluates expr, and then executes command the resultant number of times.


Here is an example of the use of repeat:

% repeat 2 echo hi there          ...display two lines. hi there hi there % _ 


8.9.6. switch .. case .. endsw

The switch command supports multiway branching based on the value of a single expression. Figure 8-28 shows the general form of a switch construct.

Figure 8-28. Description of the switch shell command.


switch (expr)
 case pattern1:
  list
  breaksw
 case pattern2:
 case pattern3:
  list2
  breaksw
default:
  defaultList
endsw

expr is an expression that evaluates to a string. pattern1, pattern2, and pattern3 may include wildcards. list1, list2, and defaultList are lists of one or more shell commands. The shell evaluates expr and then compares it to each pattern in turn, from top to bottom. When the first matching pattern is found, its associated list of commands is executed and then the shell skips to the matching endsw. If no match is found and a default condition is supplied, then defaultList is executed. If no match is found and no default condition exists, then execution continues from after the matching endsw.



[Page 319]

Here's an example of a script called "menu.csh" that makes use of a switch control structure:

# echo menu test program set stop = 0             # reset loop termination flag while ($stop == 0)       # loop until done  cat << ENDOFMENU        # display menu  1   : print the date.  2, 3: print the current  working directory  4   : exit ENDOFMENU  echo  echo -n 'your choice? '      # prompt  set reply = $<               # read response  echo ""  switch ($reply)              # process response    case "1":      date                     # display date      breaksw    case "2":    case "3":      pwd                      # display working directory      breaksw    case "4":      set stop = 1             # set loop termination flag      breaksw    default:                   # default      echo illegal choice      # error      breaksw   endsw   echo end 


Here's the output from the "menu.csh" script:

% tcsh menu.csh menu test program  1   : print the date.  2, 3: print the current working directory  4   : exit your choice? 1 Sat May 14 00:50:26 CST 2005 
[Page 320]
1 : print the date. 2, 3: print the current working directory 4 : exit your choice? 2 /home/glass 1 : print the date. 2, 3: print the current working directory 4 : exit your choice? 5 illegal choice 1 : print the date. 2, 3: print the current working directory 4 : exit your choice? 4 % _


8.9.7. while .. end

The built-in while command allows a list of commands to be repeatedly executed as long as a specified expression evaluates to true (nonzero). Figure 8-29 gives the syntax.

Figure 8-29. Description of the while shell command.


while ( expr )
 commandlist
end

The while command evaluates the expression expr, and if it is true, proceeds to execute every command in commandlist and then repeats the process. If expr is false, the while loop terminates and the script continues to execute from the command following the end. A break command causes the loop to end immediately, and a continue command causes the loop to jump immediately to the next iteration.



[Page 321]

Here's an example of a script that uses a while control structure to generate a small multiplication table:

% cat multi.csh                ...list the script. # set x = 1                      # set outer loop value while ($x <= $1)               # outer loop  set y = 1                     # set inner loop value  while ($y <= $1)              # inner loop    @ v = $x * $y               # calculate entry    echo -n $v " "              # display entry (tab in quotes)    @ y ++                      # update inner loop counter  end  echo ""                       # newline  @ x ++                        # update outer loop counter end % tcsh multi.csh 7              ...execute the script. 1       2       3        4        5       6       7 2       4       6        8        10      12      14 3       6       9        12       15      18      21 4       8       12       16       20      24      28 5       10      15       20       25      30      35 6       12      18       24       30      36      42 7       14      21       28       35      42      49 % _ 





Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net