Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Created November 7, 2016 19:19
Show Gist options
  • Save peteristhegreat/353199c4a80c84ab253eda993e61e809 to your computer and use it in GitHub Desktop.
Save peteristhegreat/353199c4a80c84ab253eda993e61e809 to your computer and use it in GitHub Desktop.
Show a back trace in bash with context lines.
# Prints the stack trace and some context lines for where the stack trace happened
# rotate the log
unlink /var/rotating_log.log
datetime=$(date +%m%d%Y_%H%M%S);
logfile="rotating_log_$datetime.log"
echo "Started on $datetime" > $logfile
#chfile mygroup 664 $logfile
ln -s $logfile rotating_log.log
# show the output in stdout and in the log file
exec &> >(tee -a $logfile)
function stack_trace() # requires a variable called $logfile
echo "stack:" >> $logfile
local frame=0
# caller is only available in bash
# http://wiki.bash-hackers.org/commands/builtin/caller
while caller $frame >> $logfile; do
((frame++))
done
echo "end of stack" >> $logfile
# show the 5 previous lines leading up to the call to stack_trace
local start=$(expr ${BASH_LINENO[0]} - 5)
context_lines=$(sed ''"$start"','"${BASH_LINENO[0]}"'!d' "${BASH_SOURCE[1]}" | nl -ba -v$start)
cat <<EOF >> $logfile
>>>
error in: ${BASH_SOURCE[1]}
$context_lines
<<<
EOF
}
# example usage
# TODO fix the bug below
echo "Bug 12345"
stack_trace()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment