## 35.16. Set Exit Status of a Shell (Script)

Most standard Unix toolbox commands return a status (Section 35.12). Your shell script should, too. This section shows how to set the right exit status for both normal exits and error exits.

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

Go to http://examples.oreilly.com/upt3 for more information on: bkedit

Here's an example, a rewrite of the bkedit script from Section 35.13. If the script can make a backup copy, the editor is run and the script returns the exit status from vi (usually 0). If something goes wrong with the copy, the script prints an error and returns an exit status of 1. Here's the script:

>     #!/bin/sh
>     if cp "$1" "$1.bak"
>     then
>         vi "$1"
>         exit   # Use status from vi
>     else
>         echo "bkedit quitting: can't make backup?" 1>&2
>         exit 1
>     fi

Here's what happens if I run it without a filename:

>     $ bkedit
>     cp: usage: cp fn1 fn2 or cp fn1 [fn2...] dir
>     bkedit quitting: can't make backup?

And here's what's left in the exit status variable:

>     $ echo $?
>     1

-- JP

Copyright © 2003 O'Reilly & Associates. All rights reserved.