Created
January 26, 2016 08:42
-
-
Save thefekete/b5a4eda341f9707aa3b0 to your computer and use it in GitHub Desktop.
Bash script to show logging/output functions based on verbosity level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# see http://stackoverflow.com/a/14203146 for more on this | |
set -e | |
verbose=0 | |
# log functions | |
error() { >&2 echo $*; } # prints to stderr always | |
warn() { (($verbose>0)) && echo $* || true; } # prints when verb is >0 | |
info() { (($verbose>1)) && echo $* || true; } # prints when verb is >1 | |
debug() { (($verbose>2)) && echo $* || true; } # prints when verb is >2 | |
verbose() { (($verbose>3)) && echo $* || true; } # prints when verb is >3 | |
USAGE=" | |
usage: | |
$(basename $0) [options] arg1 [arg2 ...] | |
options: | |
-v, --verbose increase verbosity (up to 4 v's) | |
-h, --help print this message and exit | |
Simple functions using echo for use with varying verbose levels. Try adding | |
more '-v' options and see how it works. | |
" | |
while [[ $1 == -* ]]; do | |
case $1 in | |
-v|--verbose) | |
((verbose+=1)) | |
# do not shift again! | |
;; | |
-h|--help) | |
echo "$USAGE" | |
exit | |
;; | |
*) | |
>&2 echo "$(basename $0): unknown option $1" \ | |
"(run '$(basename $0) --help' for available options)" | |
exit 1 | |
esac | |
shift | |
done | |
error "This is an error message" | |
warn "This is a warning message" | |
info "This is an info message" | |
debug "This is a debug message" | |
verbose "This is a verbose message" | |
echo "end of script" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment