[Chapter 44] 44.9 Testing Your Success
Author: Jerry Peek, Tim O'Reilly & Mike Loukides
Date: 1998-08-04T21:53:41Z

#

| Chapter 44 Shell Programming for the Uninitiated |

## 44.9 Testing Your Success

The shells let you test for success right on the command line. This gives you a very efficient way to write quick and comprehensible shell scripts.

I'm referring to the `||` and `&&` operators; in particular, the `||` operator. `comm1``||` `comm2` is typically explained as "execute the command on the right if the command on the left failed." I prefer to explain it as an "either-or" construct: "execute either comm1 or comm2." While this isn't really precise, let's see what it means in context:

>     cat filea fileb > filec || exit

This means "either cat the files or exit." If you can't cat the files (if cat returns an exit status of 1), you exit (38.4). If you can cat the files, you don't exit; you execute the left side or the right side.

I'm stretching normal terminology a bit here, but I think it's necessary to clarify the purpose of `||`. By the way, we could give the poor user an error message before flaming out:

    1>&2
    cat filea fileb > filec || {
       echo sorry, no dice 1>&2
       exit 1
    }

Similarly, `comm1``&&` `comm2` means "execute comm1 AND comm2," or execute comm2 if comm1 succeeds. (But if you can't execute the first, don't do any.) This might be helpful if you want to print a temporary file and delete it immediately.

>     lpr file && rm file

If lpr fails for some reason, you want to leave the file around. Again, I want to stress how to read this: print the file and delete it. (Implicitly: if you don't print it, don't delete it.)

- ML

44.8 Test Exit Status with the if Statement |  | 44.10 Loops That Test Exit Status