UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 47.5 Using C Shell Arrays Chapter 47
C Shell Programming...NOT
Next: IX. Miscellaneous
 

47.6 Quick Reference: C Shell switch Statement

The switch statement is used to process commands depending on the value of a variable. When you need to handle more than three choices, switch is a useful alternative to an if-then-else statement.

If the string variable matches pattern1, the first set of commands is executed; if string matches pattern2, the second set of commands is executed; and so on. If no patterns match, execute commands under the default: case. string can be specified using command substitution (9.16), variable substitution (6.8), or filename expansion (1.16). Patterns can be specified using the pattern-matching symbols *, ?, and []. breaksw is used to exit the switch after commands are executed. If breaksw is omitted (which is rarely done), the switch continues to execute another set of commands until it reaches a breaksw or endsw.

Below is the general syntax of switch, side by side with an example that processes the first command-line argument.

switch (string)   switch ($argv[1])
  case pattern1:     case -[nN]:
      commands          nroff $file | lp
      breaksw                              breaksw
  case pattern2:     case -[Pp]:
      commands          pr $file | lp
      breaksw                              breaksw

  case pattern3:     case -[Mm]:
      commands          more $file
      breaksw                              breaksw
      .                              case -[Ss]:
      .                                 sort $file
      .                                    breaksw
  default:                                    default:
      commands                   echo "Error-no such option"
                                           exit 1
      breaksw                                    breaksw
endsw                                endsw

- DG from O'Reilly & Associates' UNIX in a Nutshell (SVR4/Solaris)


Previous: 47.5 Using C Shell Arrays UNIX Power ToolsNext: IX. Miscellaneous
47.5 Using C Shell Arrays Book IndexIX. Miscellaneous

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System