I couldn’t find much mention of logging utilities for Linux shell scripting (namely Bash), so I wrote my own fairly quickly. I wanted several functions for various levels of logging (info, debug, warning, errors, etc), and a way to adjust what levels can be displayed. I followed the fairly standard convention of using numeric values for these levels and setting a “verbosity” level. If you know of an existing solution for Bash, let me know in the comments. Anyway, here’s the main idea:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | exec 3>&2 # logging stream (file descriptor 3) defaults to STDERR verbosity=2 # default to show warnings silent_lvl=0 err_lvl=1 wrn_lvl=2 inf_lvl=3 dbg_lvl=4 notify() { log $silent_lvl "NOTE: $1"; } # Always prints error() { log $err_lvl "ERROR: $1"; } warn() { log $wrn_lvl "WARNING: $1"; } inf() { log $inf_lvl "INFO: $1"; } # "info" is already a command debug() { log $dbg_lvl "DEBUG: $1"; } log() { if [ $verbosity -ge $1 ]; then # Expand escaped characters, wrap at 70 chars, indent wrapped lines echo -e "$2" | fold -w70 -s | sed '2~1s/^/ /' >&3 fi } |
I added line wrapping and indenting so users don’t have to manually put in line-breaks to get nicer looking outputs, but there is the drawback that it makes the output harder to grep. Perhaps I should add an option to disable the line wrapping.
Here is a longer example with some simple option parsing (apologies for using getopt; I’m currently looking for a better solution).
