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

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.10 Loops That Test Exit Status Chapter 44
Shell Programming for the Uninitiated
Next: 44.12 Trapping Exits Caused by Interrupts
 

44.11 Set Exit Status of a Shell (Script)

Most standard UNIX commands return a status (44.7 ) . 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.

Here's an example: a rewrite of the bkedit script from article 44.8 . 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:







1>&2
 






#!/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


Previous: 44.10 Loops That Test Exit Status UNIX Power Tools Next: 44.12 Trapping Exits Caused by Interrupts
44.10 Loops That Test Exit Status Book Index 44.12 Trapping Exits Caused by Interrupts

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System










??????????????@Mail.ru