Skip to content

Instantly share code, notes, and snippets.

Last active May 6, 2024 18:24
Show Gist options
  • Save goodmami/6556701 to your computer and use it in GitHub Desktop.
Save goodmami/6556701 to your computer and use it in GitHub Desktop.
Basic logging commands for Linux shell scripts
## Simple logging mechanism for Bash
## Author: Michael Wayne Goodman <>
## Thanks: Jul for the idea to add a datestring. See:
## Thanks: @gffhcks for noting that inf() and debug() should be swapped,
## and that critical() used $2 instead of $1
## License: Public domain; do as you wish
exec 3>&2 # logging stream (file descriptor 3) defaults to STDERR
verbosity=3 # default to show warnings
notify() { log $silent_lvl "NOTE: $1"; } # Always prints
critical() { log $crt_lvl "CRITICAL: $1"; }
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
datestring=`date +'%Y-%m-%d %H:%M:%S'`
# Expand escaped characters, wrap at 70 chars, indent wrapped lines
echo -e "$datestring $2" | fold -w70 -s | sed '2~1s/^/ /' >&3
Copy link

Hello, what does this statement means: sed '2~1s/^/ /' ?

Copy link

@MapleLove2014, that indents the wrapped lines. 2~1 means to perform the following operation on every line starting from the 2nd (every 1 line after line 2), then s/^/ / is a substitution operation that matches the beginning of each line (^) and inserts two spaces. In a terminal you might try man sed to get more info about the command.

Copy link

p1r473 commented May 4, 2024

Ive used this extensively and made some modifications - tell me what you think!

Copy link

goodmami commented May 6, 2024

@p1r473 glad you found it useful! The colors in your version are a nice touch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment