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…
As you noticed, you can define some
logfunctions likelog,log_debug,log_error, etc.It can help increasing your main code readability and hide show\nonshow logic into logging function.
log "some text"If
_V(global variable) is equal1“some text” will be printed, in other case it will not.