Showing posts with label functions. Show all posts
Showing posts with label functions. Show all posts

Thursday, November 1, 2018

Bash function to nicely output the elapsed time




The bash function:

### Function: take integer UNIXTIMESTAMP start calc the diff against the current "date +'%s'". Displays elapses timestamp as "HH:MM:SS (NNN sec)"
function printelapsed() {
    local let s=$((`date +'%s'`-$1))
    ((all=s, sec=s%60, s/=60, min=s%60, hrs=s/60))
    printf "%d:%02d:%02d (%d sec)" $hrs $min $sec $all
} ### end func

The code usage:

let STARTSTEP=$(date +'%s')   ### Start the timer
#### DO SOME STUFF HERE ###
echo "[`date +"%Y-%m-%d %H:%M:%S"`] Elapsed: `printelapsed $STARTSTEP`." >> $LOGFILE

The output:

[2018-11-01 02:51:40] Total elapsed: 0:06:39 (399 sec).