I have a traceback function in bash that works quite well (the code below), but the problem is that bash itself, when it gets into an error, does not provide backtracking or any information that will help identify the caller, which can help in debugging the problem.
eg:.
./c.sh: line 23: urgh: command not found
function backtrace () {
local deptn=${#FUNCNAME[@]}
for ((i=1; i<$deptn; i++)); do
local func="${FUNCNAME[$i]}"
local line="${BASH_LINENO[$((i-1))]}"
local src="${BASH_SOURCE[$((i-1))]}"
printf '%*s' $i ''
echo "at: $func(), $src, line $line"
done
}
Is it possible to catch bash on such errors so that I can call my own function to get this output?
at: c(), ./c.sh, line 22
at: b(), ./c.sh, line 11
at: main(), ./b.sh, line 5
Update: The final working version of the suggestions and trap traps on error:
function backtrace () {
local deptn=${#FUNCNAME[@]}
for ((i=1; i<$deptn; i++)); do
local func="${FUNCNAME[$i]}"
local line="${BASH_LINENO[$((i-1))]}"
local src="${BASH_SOURCE[$((i-1))]}"
printf '%*s' $i ''
echo "at: $func(), $src, line $line"
done
}
function trace_top_caller () {
local func="${FUNCNAME[1]}"
local line="${BASH_LINENO[0]}"
local src="${BASH_SOURCE[0]}"
echo " called from: $func(), $src, line $line"
}
set -o errtrace
trap 'trace_top_caller' ERR
source
share