Quote:
Originally Posted by lapishater276
How would i add an if statement to see whether or not the script failed?
|
You mean, how do you add an
if statement to see if one of the commands used by you script, failed?
Just about every command in existence follows the convention of generating a non-zero exit code if the operation somehow fails. Different commands may return different values depending on the nature of the error, but it's fairly safe to assume that a non-zero value means something went wrong.
The exit code is stored in the
$? variable, so a simple test would look something like this:
Code:
if [ "$?" != "0" ]; then
echo Oops, something went wrong.
exit 1
fi
Here I simply test for a non-zero value and print a simple error message before exiting the script with an exit code of 1.
Note: Every command returns an exit code, including the
if command. If you need to run multiple tests on an exit code for a specific command to deal with different error conditions, you'll have to store the contents of
$? in a different variable first. Otherwise, the first test will clear the contents of
$?, and all subsequent tests will fail.