Last active
May 3, 2025 10:36
-
-
Save ascopes/7a2f8e78eaa889a3ec939c5a6c36d10e to your computer and use it in GitHub Desktop.
Script to produce a bash stacktrace, compatible with Bash v5.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function stacktrace() { | |
if ! command -v realpath > /dev/null 2>&1; then | |
function realpath() { | |
cd "${1}" > /dev/null 2>&1 && pwd || printf "?" | |
} | |
fi | |
printf "Script stacktrace (most recent call first):\n" | |
local frame=0 | |
local line func file | |
while read -r line func file < <(caller "${frame}"); do | |
printf "\t%s:%s (file=%s)\n" "${func}" "${line}" "${file}" | |
((frame = frame + 1)) | |
done | |
printf "Process hierarchy (child processes first):\n" | |
local pid=$$ | |
local exe cwd | |
while [[ -d /proc/${pid} ]]; do | |
exe=$(cut -d $'\0' -f2 "/proc/${pid}/cmdline") | |
cwd=$(realpath "/proc/${pid}/cwd") | |
printf "\t%s (pid=%s, cwd=%s)\n" "${exe}" "${pid}" "${cwd}" | |
if ((pid <= 1)); then | |
# Root process, so we cannot go any further. | |
break | |
else | |
pid=$(cut -d ' ' -f4 "/proc/${pid}/stat") | |
fi | |
done | |
} | |
# If the script was invoked directly rather than sourced, generate | |
# some demo output. | |
if ! (return > /dev/null 2>&1); then | |
function __stacktrace_demo() { | |
function func1() { func2; } | |
function func2() { func3; } | |
function func3() { func4; } | |
function func4() { func5; } | |
function func5() { stacktrace; } | |
func1 | |
} | |
__stacktrace_demo | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment