Shell Scripting
◾
275
The following examples demonstrate further use of the wildcards. In the first case, we
are testing various possible Yes/No answers for the user. In the second case, we are com-
paring a file name against a list of possible extensions to determine how to handle the file
(in this case, we are attempting to compile the program).
echo –n Do you agree to the licensing terms of the program?
read
answer
case $answer in
[yY] | [yY][eE][sS]) ./program ;;
[nN] | [nN][oO] ) echo I cannot run the program ;;
*) echo Invalid response ;;
esac
if [ $# -eq 0 ]; then echo Error, no directory provided
else
for file in $1; do
case $file in
*.c) gcc $file ;;
*.java) javac $file ;;
*.sh)./$file ;;
*.*) echo $file is of an unknown type
*) echo $file
has no extension to match
esac
done
fi
Finally, you can alter the case statement’s behavior by using ;& instead of ;; to end an
action. With ;; the action, after executing, causes the case statement to terminate. Instead,
if an action executes
and ends with the notation ;&, then the case statement continues
by comparing the remaining lists. Thus, such a case statement could conceivably execute
multiple actions. In the following code skeleton, any combination of the first three could
match. The first case represents that the variable has a lower-case letter stored in it. If so,
it executes its action(s) but continues on to the second case because of the ;&
ending the
instruction. The second case represents that the variable has an upper-case letter stored
in it. If so, the second set of action execute and again, the instruction continues on. The
third case represents that the variable has a digit in it. In this situation, if it matches it
executes the action(s) and then the case statement terminates. If this third case does not
match, the default executes. Thus, by
mixing the ;; and ;&, we can control how far into the
case statement we continue if we have matches. With only ;; we end the case statement as
soon as we find a match.
*[a-z]*) . . . ;&
*[A-Z]*) . . . ;&
*[0-9]*) . . . ;;
*) . . .
276
◾
Linux with Operating System Concepts
7.5.6 Conditions outside of Selection Statements
There is one other form of selection statement to explore which
is a short-hand notation
for an if-then statement by using
short circuiting
, which can be applied by using && or ||.
With respect to &&, if the first half of the condition is false, there is no need to compute the
second half because it is immaterial. Similarly for ||, if the first half of the condition is true
then there is no need to compute the second half.
For instance, consider
A
>
B && B
>
C
If A is not greater than B, then there is no need to compare B to C because the entire
expression must be false. Alternatively, in
D
>
E || F
>
G
If D is greater than E, there is no need to compare F and G because
the entire expression
is true.
In Linux, we apply this concept to pair up a condition and an executable statement as
follows.
•
[
Do'stlaringiz bilan baham: