Skip to main content Logo

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

Bash Bits: Debug Logging

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

❗ This post is over ten years old. It may no longer be up to date. Opinions may have changed.

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

Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $200 credit for 60 days. Spend $25 after your credit expires and I'll get $25!

All Bash Bits can be found using this link

Debug logging can be very usefull when scripts or programs don't do what you want. 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 prints all 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 our script:

debug "This is debug output".

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

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

Example with debug logging:

[10:52:51] [remy@gateway] [ ~/conf (master) ]
$ export DEBUG_LOG=1
[10:52:56] [remy@gateway] [ ~/conf (master) ]
$ ./
### 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) ]
$ ./
Tags: bash , bash-bits , debug , logging , shell , snippets