Making shell scripts robust by checking command exit values
One great thing about unix is the ability to automate common operations with simple shell scripts – however there are risks.
One such risk is that in the case a command fails, the script can plough on regardless.
If your script does something like the following..
cp -r mydir backup
rm -rf mydir
..you should really check that the copy command was successful before deleting the directory
The following solution should work in the Korn shell and Bash
A solution is found in the built in shell variable $?
This variable contains the exit code from the last command executed.
You can use it to check the exit code for each command and terminate the script early if something goes wrong.
In my scripts, I declare the following function to do this.
It checks the $? variable, and if the exit code was anything other than zero (success) it terminates the script with an error message
{
if [ $? -ne 0 ] ; then
echo $1 1>&2
exit 1
fi
}
This function takes a parameter ($1) which determines the error message written to standard error if an error occurred.
You use it like this:
{
if [ $? -ne 0 ] ; then
echo $1 1>&2
exit 1
fi
}
cp -r mydir backup
fn_exitIfError "Failed to copy mydir to backup"
rm -rf mydir
fn_exitIfError "Failed to delete mydir"
There are alternatives to the above –>
Alternatively you can call set -e at the top of your script.
This will make the script exit if any command returns a non zero status.
In the Korn shell, you can also combine set -e with trap ERR, and implement some custom handling if something goes wrong.
However, neither of these approaches will give you a very specific error message, which is why I prefer to use the function above, even if it is more verbose.
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply