Last active
November 9, 2023 07:29
-
-
Save rene-d/fd2d2c37dfc1371255818d73f7b5f1db to your computer and use it in GitHub Desktop.
Little debugger for bash scripts
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
#!/bin/echo must be source: | |
# bash debugger | |
# Rene Devichi. https://unlicense.org | |
# Usage: `source bashdb.db` at the beginning of your script | |
# Inline version: | |
# curl -sL -o /tmp/bashdb.sh https://gist.github.com/rene-d/fd2d2c37dfc1371255818d73f7b5f1db/raw/bashdb.sh | |
# trap "rm -f /tmp/bashdb.sh" EXIT | |
# . /tmp/bashdb.sh | |
# Install (assuming ~/.local/bin exists and is on your PATH) | |
# curl -sL -o $HOME/.local/bin/bashdb.sh https://gist.github.com/rene-d/fd2d2c37dfc1371255818d73f7b5f1db/raw/bashdb.sh | |
# Use with . bashdb.sh | |
bashdb_continue= | |
bashdb_run_until= | |
bashdb_trap() | |
{ | |
local rc="$?" | |
statusline() | |
{ | |
local state=${1:-run} | |
echo -e "(${state}) \033[97m\$?=${rc}\033[0m \033[33m${BASH_SOURCE[2]}:${BASH_LINENO[1]}\033[0m \033[33m[${FUNCNAME[2]}]\033[0m \033[32m""$BASH_COMMAND""\033[0m" | |
} | |
# if stdin is not a terminal, automatically continue with a delay | |
if [[ ! -t 0 ]]; then | |
statusline | |
sleep 2 | |
return | |
fi | |
# by default do not trap shell functions | |
set +o functrace | |
if [[ $bashdb_continue ]]; then | |
statusline | |
return | |
fi | |
if [[ $bashdb_run_until ]]; then | |
if [[ ${BASH_LINENO[0]} -lt $bashdb_run_until ]]; then | |
statusline | |
return; | |
fi | |
bashdb_run_until= | |
fi | |
while true; do | |
statusline dbg | |
read -r -n1 -s a | |
case "$a" in | |
''|n) break ;; | |
C) bashdb_continue=1 ; break ;; | |
r|R) | |
read -r -e -p "line ? " a | |
if [[ $a ]]; then bashdb_run_until=$a; fi | |
break | |
;; | |
s) | |
set -o functrace | |
break | |
;; | |
p|\?) | |
read -r -e -p "variable ? " a | |
if [[ $a ]]; then | |
echo -e "$a = \033[1;31m${!a}\033[0m" | |
fi | |
;; | |
e) echo -ne "\033[1;31m"; env ; echo -ne "\033[0m" ;; | |
!) ${BASH} ;; | |
v) | |
read -r -e -p "eval> " a | |
eval "$a" | |
;; | |
q|Q) echo "quit"; exit 0 ;; | |
*) echo -e "Unknown command \033[1;35m$a\033[0m. "\ | |
"\033[1;35mn\033[0m\033[0m=next "\ | |
"\033[1;35ms\033[0m=step into "\ | |
"\033[1;35mr\033[0m=run until "\ | |
"\033[1;35mC\033[0m=continue "\ | |
"\033[1;35mp\033[0m=print "\ | |
"\033[1;35me\033[0m=env "\ | |
"\033[1;35m!\033[0m=shell "\ | |
"\033[1;35mq\033[0m=quit "\ | |
"\033[1;35mv\033[0m=eval" | |
esac | |
done | |
} | |
trap bashdb_trap debug |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment