Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 540
nosatalian Avatar asked Apr 27 '11 21:04

nosatalian


1 Answers

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.

like image 116
John Zwinck Avatar answered Nov 03 '22 19:11

John Zwinck