A log function for bash

So if you are making scripts in bash, it’s sometimes useful to print debug information to the screen. You can use ‘echo‘ but why not use something a bit more fancy.

#!/bin/bash

log_now="$(date +%s)sec"
function log {
>&2 echo -e "$(TZ=UTC date --date now-$log_now +%H:%M:%S.%N)\t${BASH_SOURCE}:${BASH_LINENO}:${FUNCNAME[1]}\t${*}"
}

This little function will print out a timestamp relative to the start of the script. (Easily changed if you want walltime instead). It also prints to stderr, so as not to interfere with output redirected to files. It will also show you the file, line and function where you called the log function, so you can easily trace back where a problem occurred.

For example:

function bla {
log "123"
}

bla                            # 00:00:00.164662807      ./myscript.sh:9:bla       123
log "tra la la la a"           # 00:00:00.177854026      ./myscript.sh:13:main     tra la la la a

Note that this uses a number of BASH specific variables, so it’s not portable.