How to Handle Error/Exception in Shell Script

Exception handling in shell scripting?

There is not really a try/catch in bash (i assume you're using bash), but you can achieve a quite similar behaviour using && or ||.

In this example, you want to run fallback_command if a_command fails (returns a non-zero value):

a_command || fallback_command

And in this example, you want to execute second_command if a_command is successful (returns 0):

a_command && second_command

They can easily be mixed together by using a subshell, for example, the following command will execute a_command, if it succeeds it will then run other_command, but if a_command or other_command fails, fallback_command will be executed:

(a_command && other_command) || fallback_command

How to handle error/exception in shell script?

You can check for the exit status of each command, as freetx answered, but this is manual error checking rather than exception handling. The standard way to get the equivalent of exception handling in sh is to start the script with set -e. That tells sh to exit with a non-zero status as soon as any executed command fails (i.e. exits with a non-zero exit status).

If it is intended for some command in such a script to (possibly) fail, you can use the construct COMMAND || true, which will force a zero exit status for that expression. For example:

#!/bin/sh

# if any of the following fails, the script fails
set -e
mkdir -p destdir/1/2
mv foo destdir/1/2
touch /done || true # allowed to fail

Another way to ensure that you are notified when things go wrong in a script invoked by cron is to adhere to the Unix convention of printing nothing unless an error ocurred. Successful runs will then pass without notice, and unsuccessful runs will cause the cron daemon to notify you of the error via email. Note that local mail delivery must be correctly configured on your system for this to work.

Is there a TRY CATCH command in Bash

Is there a TRY CATCH command in Bash?

No.

Bash doesn't have as many luxuries as one can find in many programming languages.

There is no try/catch in bash; however, one can achieve similar behavior using && or ||.

Using ||:

if command1 fails then command2 runs as follows

command1 || command2

Similarly, using &&, command2 will run if command1 is successful

The closest approximation of try/catch is as follows

{ # try

command1 &&
#save your output

} || { # catch
# save log for exception
}

Also bash contains some error handling mechanisms, as well

set -e

it stops your script if any simple command fails.

And also why not if...else. It is your best friend.

How to handle errors in shell script

/* the status of your last command stores in special variable $?, you can define variable for $? doing export var=$? */

unzip filename
export unzipStatus=$?
./script1.sh
export script1Status=$?
if [ !["$unzipStatus" || "$script1Status"]]
then
echo "Everything successful!"
else
echo "unsuccessful"
fi

Error handling in shell script

To illustrate Ignacio's answer (use following protocol: first check if lockfile exists and then install the trap), you can solve the problem like this:

$ cat test2.sh
if [ -f run_script.lck ]; then
echo Script $0 already running
exit 1
fi
trap "rm -f run_script.lck" EXIT
# rest of the script ...

Is Exception handling possible in Unix shell script, which includes calling another scripts internally

Not sure if this works in sh, but it works in bash.
I made a try / except tool out of this, but it will work here too I believe.

#! /bin/bash

try() {
exec 2> /dev/null
#direct stderr out to /dev/null

#main block
input_function="$1"

#fallback code
catch_function="$3"

#open a sub shell
(

#tell it to exit upon encountering an error
set -e

#main block
"$@"

)

#if exit code of above is > 0, then run fallback code
if [ "$?" != 0 ]; then
$catch_function
else
#success, it ran with no errors
test
fi

#put stderr back into stdout
exec 2> /dev/tty
}

An example of using this would be:

try [function 1] except [function 2]

Function 1 would be main block of code, and 2 would be fallback function/block of code.
Your first function could be:

run() {
/path/to/external/script
}

And your second can be whatever you want to fall back on.
Hope this helps.

Raise error in a Bash script

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.



Related Topics



Leave a reply



Submit