Skip to content

Instantly share code, notes, and snippets.

@Jcpetrucci
Last active July 31, 2022 01:48
Show Gist options
  • Save Jcpetrucci/5acfc6278fbe7fad2943655627cb65a1 to your computer and use it in GitHub Desktop.
Save Jcpetrucci/5acfc6278fbe7fad2943655627cb65a1 to your computer and use it in GitHub Desktop.
better Bash trace
#!/bin/bash
# Define variables for adjustable verbosity
verbosity=2 #Start counting at 2 so that any increase to this will result in a minimum of file descriptor 3. You should leave this alone.
maxverbosity=5 #The highest verbosity we use / allow to be displayed. Feel free to adjust.
# Parse requested verbosity level and whether we're logging or not
while getopts ":vl" opt; do
case $opt in
v) (( verbosity=verbosity+1 ));;
l) log="true" ;;
esac
done
# Opt-out logging: Use `script` utility to log output in case you want to review it later. We call this script again but inside of `script` and add '-l' to prevent recursion. If you don't want logs, add '-l' when you invoke the script.
[[ "$log" == "true" ]] || exec script --return --quiet --command "$0 -l $*" --append ${0}.log
printf "%s %d. %s\n" "Verbosity level set to:" "$verbosity" "Increase with '-v[v]'."
for v in $(seq 3 $verbosity) #Start counting from 3 since 1 and 2 are standards (stdout/stderr).
do
(( "$v" <= "$maxverbosity" )) && eval exec "$v>&2" #Don't change anything higher than the maximum verbosity allowed.
done
for v in $(seq $(( verbosity+1 )) $maxverbosity ) #From the verbosity level one higher than requested, through the maximum;
do
(( "$v" > "2" )) && eval exec "$v>/dev/null" #Redirect these to bitbucket, provided that they don't match stdout and stderr.
done
function debug(){
printf '\tdebug: %s%s%s\n' "$(tput setab 0)" "$BASH_COMMAND" "$(tput sgr0)" >&3
}
trap 'debug' DEBUG
printf '%s running at %s\n' "$(basename $0)" "$(date)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment