bashloggingverbosity

Elegant way for verbose mode in scripts?


When I write bash scripts I usually get the verbose mode this way (simplified):

_V=0

while getopts "v" OPTION
do
  case $OPTION in
    v) _V=1
       ;;
  esac
done

and then every time I want a "verbose output" I type this:

[ $_V -eq 1 ] && echo "verbose mode on" || echo "verbose mode off"

or for example this:

[ $_V -eq 1 ] && command -v || command

Is there a way to do it more elegant? I was thinking about defining a function named "verbose" and type it instead of [ $_V -eq 1 ], but this would only be a tiny improvement.

I'm sure, there is more common way to do it…


Solution

  • As you noticed, you can define some log functions like log, log_debug, log_error, etc.

    function log () {
        if [[ $_V -eq 1 ]]; then
            echo "$@"
        fi
    }
    

    It can help increasing your main code readability and hide show\nonshow logic into logging function.

    log "some text"

    If _V(global variable) is equal 1 "some text" will be printed, in other case it will not.