2

Is there some way for a bash script to explicitly trigger a trap that is looking for an ERR signal (which is a special signal that can be explicitly called via kill, see https://stackoverflow.com/a/26261518/8236733)? Have a trap file of the form

#!/bin/bash
error() {#do stuff like alert people via email}
trap 'error ${LINENO} $tablename' ERR

and a script of the form

#!/bin/bash

# trap to catch errors
source '/home/mapr/etl_scripts/clarity/lib.trap.sh'

{#try stuff} || {#catch stuff; exit 1;}

I had thought that the exit 1 would be enough to signal the trap, but this does not seem to be the case. Is there some other way to intentionally trigger the trap from within the script? Thanks.

lampShadesDrifter
  • 3,925
  • 8
  • 40
  • 102

1 Answers1

2

The ERR trap is only executed when a command run by the shell fails, not when the shell itself exits with non-zero exit status. For your case, you want to use an EXIT handler that tests the exit status.

trap 'rv=$?; if [ "$rv" -ne 0 ]; then error $LINENO $tablename; fi' EXIT
lampShadesDrifter
  • 3,925
  • 8
  • 40
  • 102
chepner
  • 497,756
  • 71
  • 530
  • 681