44.8 Test Exit Status with the if Statement
If you are going to write a shell script of any complexity at all,
you need some way to write "conditional expressions." Conditional
expressions are nothing more than statements that have a value of
"true" or "false": like "Have I gotten dressed today?" or "Is it
before 5 p.m.?" or "Does the file indata
exist?" or "Is the value
of The UNIX shell is a complete programming language. Therefore, it allows you to write "if" statements with conditional expressions - just like C, Basic, Pascal, or any other language. Conditional expressions can also be used in several other situations; but most obviously, they're the basis for any sort of if statement. Here's the syntax of an if statement for the Bourne shell: if You can omit the else and the block of code following it. However, you can't omit the then or the fi . If you want to omit the then (i.e., if you want to do something special when condition is false, but nothing when it is true), write the statement like this: if
Note that this uses a special null command, a
colon ( Don't forget the fi terminating the statement. This is a surprisingly common source of bugs. (At least for me.) Another common debugging problem: the manual pages that discuss this material imply that you can smash the if , the then , and the else onto one line. Well, it's true, but it's not always easy. Do yourself a favor: write your if statements exactly like the one above. You'll rarely be disappointed, and you may even start writing programs that work correctly the first time.
Here's a real-life example: a shell script named bkedit
that makes a
backup copy of a file before editing it.
If cp
returns a zero status, the script edits the file; otherwise, it
prints a message.
(The
You can try typing in that shell script and running it.
Or, just type in
the lines (starting with the The if statement is often used with a command named test (44.20 ) . The test command does a test and returns an exit status of 0 or 1. - , |
|