brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: FUNCNAME and BASH_LINENO print a stack trace from a bash script

Bash
~/tips/tip-bash-funcname-stack-trace

die() { echo "error: $*" >&2; stack >&2; exit 1; }

Show which chain of function calls led to an error in a longer script.

In a script with many small functions, an error message from deep inside tells you what went wrong, not how the script got there. Bash keeps the call stack in three arrays you can print.

FUNCNAME holds the function names, newest first. BASH_SOURCE the file of each, and BASH_LINENO the line where each was called:

stack() {
  local i
  for ((i=1; i<${#FUNCNAME[@]}; i++)); do
    echo "  ${FUNCNAME[i]}() at ${BASH_SOURCE[i]}:${BASH_LINENO[i-1]}"
  done
}
die() { echo "error: $*" >&2; stack >&2; exit 1; }

Call die "config missing" from a function load that main called, and you get the error followed by die, load and main with their file and line numbers. The loop starts at 1 to skip stack itself.

I like having this in a small library that several scripts source, because then every die shows where it came from without extra work.

The i-1 is not a typo: BASH_LINENO is shifted by one compared with the other two arrays, which is confusing the first time. The caller builtin gives the same information one frame at a time if you prefer that. Line numbers can be off inside code that was sourced or run through eval.

Further reading: Bash manual: Bash Variables (FUNCNAME, BASH_LINENO)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link