Raise error in a Bash script

Naveen Kumar picture Naveen Kumar · May 6, 2015 · Viewed 96.1k times · Source

I want to raise an error in a Bash script with message "Test cases Failed !!!". How to do this in Bash?

For example:

if [ condition ]; then
    raise error "Test cases failed !!!"
fi

Answer

ForceBru picture ForceBru · May 6, 2015

This depends on where you want the error message be stored.

You can do the following:

echo "Error!" > logfile.log
exit 125

Or the following:

echo "Error!" 1>&2
exit 64

When you raise an exception you stop the program's execution.

You can also use something like exit xxx where xxx is the error code you may want to return to the operating system (from 0 to 255). Here 125 and 64 are just random codes you can exit with. When you need to indicate to the OS that the program stopped abnormally (eg. an error occurred), you need to pass a non-zero exit code to exit.

As @chepner pointed out, you can do exit 1, which will mean an unspecified error.