Korn Shell: Show elapsed time in a specific format

kshtime

In a log file, I need to print the Elapsed time, in the following format:

"Process completed %s - Elapsed %s",
<time now in HH:MM:SS format>,
<difference from start date to end date in HH:MM:SS format>

Example:

Process completed 23:57:59 - Elapsed 103:22:59

How could I achieve this?

Best Answer

Ksh has a special parameter SECONDS which always contains the number of seconds since the epoch. Evaluating $SECONDS at the beginning and at the end of the job gives you the start and end times, and the difference is the elapsed time.

Unix time doesn't take leap seconds into account: a day in Unix time is always exactly 86400 seconds. Therefore time-of-day arithmetic on Unix time is easy.

start=$SECONDS
…
end=$SECONDS
elapsed=$((end - start))
printf 'Process completed %d:%02d:%02d - Elapsed %d:%02d:%02d\n' \
       $((end / 3600)) $((end / 60 % 60)) $((end % 60)) \
       $((elapsed / 3600)) $((elapsed / 60 % 60)) $((elapsed % 60))