Skip to content
shellhacks.dev
Debugging

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.

1 min read
Summarize in AI

A helper function fails, and the message should say which line of the script called it.

Shell
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.sh
Text
fail called from line 11
11 outer demo.sh
13 main demo.sh

The 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.

Share

More snippets

Debugging

Stop on the first error and show where

Report where a script failed with trap '...' ERR and set -E. LINENO gives the line, BASH_COMMAND the command and $? the status, even inside functions.

1 min read
Debugging

Print each line as it is read

Print every script line as the shell reads it, before expansion, with set -v. Pair it with set -x to see the source line and the expanded command.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.