I am writing a custom debugger for bash scripts using the DEBUG trap. I stumbled upon negative line numbers when printing stacktraces using caller.
It seems like caller's output is different, when I call it inside a trap method which is used from a nested call.
debug.sh:
d() {
if [[ "${BASH_COMMAND}" == echo* ]] ; then
echo ">> $(caller 0) | $(caller 1) | ${BASH_COMMAND} <<"
fi
}
shopt -s extdebug
set -o functrace
trap d DEBUG
test.sh:
echo foo
f() {
echo bar
}
f
echo end
When I call my script with bash --rcfile debug.sh -i test.sh
I get
>> 3 main test.sh | | echo foo <<
foo
>> -2 f test.sh | 8 main test.sh | echo bar <<
bar
>> 10 main test.sh | | echo end <<
end
To compare
compare.sh:
echo() {
/bin/echo ">> $(caller 0) | $(caller 1) | echo "$@" <<"
/bin/echo "$@"
}
I print the information without a trap bash --rcfile compare.sh -i test.sh
>> 3 main test.sh | | echo foo <<
foo
>> 1 f test.sh | 8 main test.sh | echo bar <<
bar
>> 10 main test.sh | | echo end <<
end
There is a similar question how to get the original caller lineno when executing a function returning a non-zero value which misses both an explanation for bash's behaviour and a solution working for this scenario.
Assuming bash calculates something wrong in the trap I already tried to recalculate the correct linenumbers by investigating where the function definitions lie, but couldn't find any reasonable way.