Skip to main content

Raymii.org Logo (IEC resistor symbol)logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash Bits: Debug Logging

Published: 15-09-2013 | Author: Remy van Elst | Text only version of this article


Table of Contents


Bash Bits are small examples and tips for Bash Scripts. This bash bit shows youhow to add debug logging to a bash script.

If you like this article, consider sponsoring me by trying out a Digital OceanVPS. With this link you'll get $100 credit for 60 days). (referral link)

All Bash Bits can be found using this link

Debug logging can be very usefull when scripts or programs don't do what youwant. I use it in most of my scripts.

First we create a simple one line function named debug:

function debug() { ((DEBUG_LOG)) && echo "### $*"; }

As you can see, very simple. If the variable DEBUG_LOG is set, then it printsall the text given to the function. If the variable is not set, it does nothing.

Now if we want to debug log something, we place the following line in ourscript:

debug "This is debug output".

When we want to see the debug logging, before we run the script, we set thevariable DEBUG_LOG to 1:

export DEBUG_LOG=1# or just for this script run:DEBUG_LOG=1 ./script.sh

Example with debug logging:

[10:52:51] [remy@gateway] [ ~/conf (master) ]$ export DEBUG_LOG=1[10:52:56] [remy@gateway] [ ~/conf (master) ]$ ./setup.sh### vimrc done### screenrc done### bash done

Example without debug logging:

[10:53:11] [remy@gateway] [ ~/conf (master) ]$ unset DEBUG_LOG[10:53:11] [remy@gateway] [ ~/conf (master) ]$ ./setup.sh
Tags: bash, bash-bits, debug, logging, shell, snippets