Name

switch

Synopsis

    switch

Process commands depending on a string value. When you need to handle more than three choices, switch is a useful alternative to an if-then-else statement. If the string matches pattern1, the first set of commands executes; if string matches pattern2, the second set of commands executes; and so on. If no patterns match, the set of commands under the default case executes. string can be specified using command substitution, variable substitution, or filename expansion. Patterns can be specified using the pattern-matching symbols *, ?, [, and ]. breaksw exits 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. Here 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

Get Unix in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.