Korn Shell: Show elapsed time in a specific format
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))
Like this (Warning: those of a sensitive disposition look away now - this is old school ksh):
t1=`date '+%H:%M:%S'`
sleep 2
t2=`date '+%H:%M:%S'`
t1h=`expr $t1 : '\(..\):.*'`
t2h=`expr $t2 : '\(..\):.*'`
t1m=`expr $t1 : '..:\(..\).*'`
t2m=`expr $t2 : '..:\(..\).*'`
t1s=`expr $t1 : '..:..:\(..\)'`
t2s=`expr $t2 : '..:..:\(..\)'`
hdiff=`expr $t2h - $t1h`
mdiff=`expr $t2m - $t1m`
sdiff=`expr $t2s - $t1s`
if [ $tm1 -gt $tm2 ];then
hdiff=`expr $hdiff - 1`
mdiff=`expr $tm1 - $tm2`
fi
if [ $ts1 -gt $ts2 ];then
mdiff=`expr $mdiff - 1`
sdiff=`expr $sm1 - $sm2`
fi
if [ $hdiff -lt 10 ];then
hdiff="0$hdiff"
fi
if [ $mdiff -lt 10 ];then
mdiff="0$mdiff"
fi
if [ $sdiff -lt 10 ];then
sdiff="0$sdiff"
fi
echo "Elapsed time $hdiff:$mdiff:$sdiff"