Print the call stack
Find out which line called a function with the caller builtin in Bash. It prints the line number, function name and script file of any frame.
A helper function fails, and the message should say which line of the script called it.
cat > demo.sh <<'EOF'
#!/bin/bash
fail() {
echo "fail called from line $(caller 0 | cut -d' ' -f1)" >&2
local frame=0
while caller "$frame" >/dev/null; do
caller "$frame"
frame=$((frame + 1))
done
}
outer() {
fail
}
outer
EOF
bash demo.shfail called from line 11
11 outer demo.sh
13 main demo.shThe caller builtin prints the line number, the function name and the source file of a frame in the call stack, where frame 0 is the caller of the current function. It exits 1 when there is no such frame, so a loop over increasing numbers prints the whole stack, as the manual describes. Here fail was called on line 11, by outer, which main called on line 13.
With no argument caller prints only the line and file of the immediate caller. The builtin needs extdebug for argument details, which also changes other behavior of the shell, so avoid turning that on in production. It is a Bash feature and does not exist in dash.