2.2 Control Flow - Case: Done
2.2 Control Flow - Case: Done
The command
create alpha beta
ensures that two empty files alpha and beta exist and are empty. The notation >file may be used on its own to create or clear the contents of a file. Notice also that a semicolon (or newline) is required before done.
$# is the string 1 and the standard input is copied onto the end of file using the cat command.
append file1 file2
appends the contents of file1 onto file2. If the number of arguments supplied to append is other than 1 or 2 then a message is printed indicating proper usage.
The shell attempts to match word with each pattern, in the order in which the patterns appear. If a match is found the associated command-list is executed and execution of the case is complete. Since * is the pattern that matches any string it can be used for the default case.
A word of caution: no check is made to ensure that only one pattern matches the case argument. The first match found defines the set of commands to be executed. In the example below the commands following the second * will never be executed.
case $# in *) ... ;; *) ... ;; esac
Another example of the use of the case construction is to distinguish between different forms of an argument. The following example is a fragment of a cc command.
for i do case $i in -[ocs])
... ;;
-*) echo \'unknown flag $i\' ;; *.c) /lib/c0 $i ... ;; *) echo \'unexpected argument $i\' ;; esac done
To allow the same commands to be associated with more than one pattern the case command provides for alternative patterns separated by a |. For example,
case $i in -x|-y) esac ...
is equivalent to