basherror-handlingbash-trap

Get function backtrace in bash from trap handler (using caller)


I know that you can use 'caller' to get a backtrace of function calls in bash:

#! /bin/bash
Backtrace () {
   echo "Backtrace is:"
   i=0
   while caller $i
   do
      i=$((i+1))
   done
}
myFunc () {
   Backtrace
}
myFunc

Prints:

Backtrace is:
11 myFunc ./test.sh
13 main ./test.sh

My question is, lets say I have a script which uses 'set -e' to terminate on any unchecked failure. Is it possible to get a line number of where the script failed (and its callers)

I've tried naively doing: trap 'Backtrace' EXIT, but that gives me '1 main ./test.sh' rather than the line number of the failing command


Solution

  • I'm not sure if it will work, but try adding ERR to your list of trap'd signals. Maybe your code will be invoked before the set -e stuff takes over, in which case you'll be back in business.