Search code examples
debuggingbashgetopt

How to parametrize verbosity of debug output (BASH)?


During the process of writing a script, I will use the command's output in varying ways, and to different degrees - in order to troubleshoot the task at hand.. For example, in this snippet, which reads an Application's icon resource and returns whether or not it has the typical .icns extension...

icns=`defaults read /$application/Contents/Info CFBundleIconFile`
    if ! [[ $icns =~ ^(.*)(.icns)$ ]]; then
        echo -e $icns "is NOT OK YOU IDIOT!  **** You need to add .icns to "$icns"."
    else 
        echo -e $icns "\t Homey, it's cool.  That shits got its .icns, proper."
    fi

Inevitably, as each bug is squashed, and the stdout starts relating more to the actual function vs. the debugging process, this feedback is usually either commented out, silenced, or deleted - for obvious reasons.

However, if one wanted to provide a simple option - either hardcoded, or passed as a parameter, to optionally show some, all, or none of "this kind" of message at runtime - what is the best way to provide that simple functionality? I am looking to basically duplicate the functionality of set -x but instead of a line-by rundown, it would only print the notifications that I had architected specificically.

It seems excessive to replace each and every echo with an if that checks for a debug=1|0, yet I've been unable to find a concise explanation of how to implement a getopts/getopt scheme (never can remember which one is the built-in), etc. in my own scripts. This little expression seemed promising, but there is very little documentation re: 2>$1 out there (although I'm sure this is key to this puzzle)

[ $DBG ] && DEBUG="" || DEBUG='</dev/null'
check_errs() {
    # Parameter 1 is the return code Para. 2 is text to display on failure.
    if [ "${1}" -ne "0" ]; then
        echo "ERROR # ${1} : ${2}"
    else
        echo "SUCESSS  "
    fi }

Any concise and reusable tricks to this trade would be welcomed, and if I'm totally missing the boat, or if it was a snake, and it would be biting me - I apologize.


Solution

  • One easy trick is to simply replace your "logging" echo comamnd by a variable, i.e.

    TRACE=:
    if test "$1" = "-v"; then
        TRACE=echo
        shift
    fi
    
    $TRACE "You passed the -v option"
    

    You can have any number of these for different types of messages if you wish so.