I am writing a library and would want to detect where from a RETURN trap was called. Kindly consider the following example:
#!/bin/bash
on_return() {
echo "on_return: ${BASH_SOURCE[1]}:${BASH_LINENO[1]}:${FUNCNAME[1]}() returned" >&2
declare -p BASH_SOURCE BASH_LINENO FUNCNAME
echo
}
set -o functrace
trap 'on_return' RETURN
f() {
return 101
}
f
. <(echo '
echo "FROM INSIDE SOURCE:"
declare -p BASH_SOURCE BASH_LINENO FUNCNAME
echo
f
return 102
')
On Bash5.3 on archlinux this prints the following, with my comment:
on_return: ./test.sh:15:f() returned # correct!
declare -a BASH_SOURCE=([0]="./test.sh" [1]="./test.sh" [2]="./test.sh")
declare -a BASH_LINENO=([0]="12" [1]="15" [2]="0")
declare -a FUNCNAME=([0]="on_return" [1]="f" [2]="main")
FROM INSIDE SOURCE:
declare -a BASH_SOURCE=([0]="/dev/fd/63" [1]="./test.sh")
declare -a BASH_LINENO=([0]="17" [1]="0")
declare -a FUNCNAME # FUNCNAME is only set inside functions
on_return: ./test.sh:5:f() returned # correct!
declare -a BASH_SOURCE=([0]="./test.sh" [1]="./test.sh" [2]="/dev/fd/63" [3]="./test.sh")
declare -a BASH_LINENO=([0]="12" [1]="5" [2]="17" [3]="0")
declare -a FUNCNAME=([0]="on_return" [1]="f" [2]="source" [3]="main")
# ^^^^^^^^^^^^ - here it is
on_return: ./test.sh:0:main() returned # wrong, source returned
declare -a BASH_SOURCE=([0]="./test.sh" [1]="./test.sh")
declare -a BASH_LINENO=([0]="17" [1]="0")
declare -a FUNCNAME=([0]="on_return" [1]="main") # no source in RETURN trap from source?
Because source is not present in FUNCNAME when sourcing a script, is there a way to know if RETURN trap is called from a source script return or from a function return?