Tag Archives: Debug

Sample debug output code for BASH/SHELL

When trying to debug your own scripts it can be difficult to see exactly what you want.  Pages of white text scrolling across the screen.  Here is a quick flexible function that can make life a whole lot easier by setting different debug values and instead of using echo, use the function name.

    #################################################
    # Variable Declarations
    #
    #What output to show on screen
    #debug levels:
    # 0 is no debug or logging.
    # 1 is basic output only (gree text)
    # 2 is basic output plus basic debug  (adds yellow text)
    # 3 is show everything (adds red text)
    debuglevel=2
     
    #log to file
    log=0
     
    #where the logfile is located
    logfile="/dev/null"
     
    #################################################
    #  functions
    output(){
            if [ $debuglevel -gt "0" ] && [ $1 = "1" ];
            then
                    /bin/echo -e "`/bin/date +"%m-%d-%Y %r"`:\e[00;32m $2\e[00m"
            fi
            if [ $debuglevel -gt "1" ] && [ $1 = "2" ];
            then
                    /bin/echo -e "`/bin/date +"%m-%d-%Y %r"`:\e[01;33m $2\e[00m"
            fi
            if [ $debuglevel -gt "2" ] && [ $1 = "3" ];
            then
                    /bin/echo -e "`/bin/date +"%m-%d-%Y %r"`:\e[00;31m $2\e[00m"
            fi
            if [ $log -eq "1" ];
            then
                    /bin/echo `/bin/date +"%m-%d-%Y %r"` :  $@ >> $logfile
            fi
    }

    #################################################
    # Code
    #
    output "1" "this is normal output"
    output "2" "this is basic debug output"
    output "3" "this is everything output"

Copy this into a basic script and run it, adjust the debuglevel variable at the top to see different output.  I know this will help me in the future and hope it will help others as well.