home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Unix Power ToolsUnix Power ToolsSearch this book

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.

Figure 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:

if cp "$1" "$1.bak"
    vi "$1"
    exit   # Use status from vi
    echo "bkedit quitting: can't make backup?" 1>&2
    exit 1

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 $?

-- JP

Library Navigation Links

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