Skip to content

Instantly share code, notes, and snippets.

@lynsei
Forked from pasela/error_handling_example.sh
Created September 26, 2023 16:52
Show Gist options
  • Save lynsei/7f8994ab651e58baad44ee2c3af13231 to your computer and use it in GitHub Desktop.
Save lynsei/7f8994ab651e58baad44ee2c3af13231 to your computer and use it in GitHub Desktop.
[bash]error handling and error report example
#!/bin/bash
#
# error handling and error report example
#
set -e
# logfile
LOGFILE=`mktemp`
on_error()
{
# restore
exec 1>&3- 2>&4-
# send email, syslog and so on
echo "an error occured"
echo "----------------"
cat $LOGFILE
}
on_exit()
{
# do something
rm -f $LOGFILE
}
trap "on_error" ERR
trap "on_exit" EXIT
# save STDOUT, STDERR and redirect to logfile
exec 3>&1 4>&2
exec 1>$LOGFILE 2>&1
# do something
echo hoge
do_something_in_which_errors_may_occur
echo done
# restore STDOUT, STDERR and close temporary descriptor
exec 1>&3- 2>&4-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment