简体   繁体   中英

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

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.

if the trap is a result of a non-zero return-code, you can figure this out by trapping SIGCHLD and checking if $? -eq 0 $? -eq 0

The downside to this is that the trap will fire any time a child process returns. But you can just short-circuit with the [[ $? -eq 0 ]] return [[ $? -eq 0 ]] return

See trap fails to catch SIGSEGV for more detail.

Sorry if I misunderstood your question, hopefully this is helpful. I know your question is not specific to SIGSEGV, but it applies to any time set -e causes an exit due to a non-zero status code, so should still be applicable

EDIT: To save you the suspense, to trap SIGCHLD, you use trap <expression> CHLD , not trap <expression> SIGCHLD as most reasonable people assume:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM