Last active
April 6, 2022 03:43
-
-
Save wwalker/787e70b7b9a3d9648a3d to your computer and use it in GitHub Desktop.
Bash -x tracing without the clutter
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/bash | |
# the following sets up a bash script to write the -x tracing to a log file | |
# in /tmp, with a meaningful, unique name, and a trap to remove it if the | |
# script completes successfully. Therefore, if the script fails, in any | |
# way, the log is there to peruse. If it succeeds (exit 0) then nothing | |
# is left behind | |
# Set up a function to remove the trace file on successful run (exit 0) | |
cleanup_trace_file() { | |
if [[ "$?" == 0 ]] | |
then | |
/bin/rm $BASH_TRACE_FILE | |
else | |
printf "$0 died. Trace file: $BASH_TRACE_FILE\n" | |
fi | |
} | |
# Set up a tracing prompt that gives date and time info | |
# e.g., ++10:01:51.536573097 sort -u | |
# Using PS4 means that this will Not affect the tracing of child processes | |
PS4='+\t.$(date +%N) ' | |
# Set up trace output redirection | |
BASH_TRACE_FILE="/tmp/$(basename $0)-$LOGNAME.trace.$(date +%F_%T).$$" | |
exec {BASH_XTRACEFD}>$BASH_TRACE_FILE | |
set -x -e -o pipefail | |
trap cleanup_trace_file 0 | |
# What follows is a simple test to show that it works | |
echo stdout | |
echo stderr 1>&2 | |
Y=0 | |
exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment