Наши партнеры

11.4. Testing and Branching

The case and select
constructs are technically not loops, since they do not iterate the
execution of a code block. Like loops, however, they direct
program flow according to conditions at the top or bottom of
the block.

Controlling program flow in a code
block

case (in) / esac

The case construct is the shell
scripting analog to switch in C/C++.
It permits branching to one of a number of code blocks,
depending on condition tests. It serves as a kind of
shorthand for multiple if/then/else
statements and is an appropriate tool for creating
menus.

case "$variable" in

═"$condition1" ) ═command... ═;;

═"$condition2" ) ═command... ═;;

esac

Quoting the variables is not mandatory,
since word splitting does not take place.

Each test line
ends with a right paren ).

Each condition block ends
with a double semicolon
;;.

If a condition tests
true, then the associated
commands execute and the case
block terminates.

The entire case
block ends with an esac
(case spelled backwards).

Example 11-24. Using case

#!/bin/bash
# Testing ranges of characters.
echo; echo "Hit a key, then hit return."
read Keypress
case "$Keypress" in
[[:lower:]] ) echo "Lowercase letter";;
[[:upper:]] ) echo "Uppercase letter";;
[0-9] ) echo "Digit";;
* ) echo "Punctuation, whitespace, or other";;
esac # Allows ranges of characters in [square brackets],
#+ or POSIX ranges in [[double square brackets.
# In the first version of this example,
#+ the tests for lowercase and uppercase characters were
#+ [a-z] and [A-Z].
# This no longer works in certain locales and/or Linux distros.
# POSIX is more portable.
# Thanks to Frank Wang for pointing this out.
# Exercise:
# --------
# As the script stands, it accepts a single keystroke, then terminates.
# Change the script so it accepts repeated input,
#+ reports on each keystroke, and terminates only when "X" is hit.
# Hint: enclose everything in a "while" loop.
exit 0