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
exist?" or "Is the value
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:
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:
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
that makes a
backup copy of a file before editing it.
returns a zero status, the script edits the file; otherwise, it
prints a message.
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. The test command does a test and returns an exit status of 0 or 1.