Latheesan
Latheesan

Reputation: 24116

formatting bash/shell script time to days, hours, minutes and second

I have a backup script which is written in bash/shell scripting language. I calculate the total runtime/execution time by doing this:

#!/bin/bash

# start time
res1=$(date +%s.%N)

### do some work here

# end time & calculate
res2=$(date +%s.%N)
dt=$(echo "$res2 - $res1" | bc)
dd=$(echo "$dt/86400" | bc)
dt2=$(echo "$dt-86400*$dd" | bc)
dh=$(echo "$dt2/3600" | bc)
dt3=$(echo "$dt2-3600*$dh" | bc)
dm=$(echo "$dt3/60" | bc)
ds=$(echo "$dt3-60*$dm" | bc)

# finished
printf " >>> Process Completed - Total Runtime (d:h:m:s) : %d:%02d:%02d:%02.4f\n" $dd $dh $dm $ds
echo " "
exit 0

This outputs something like this: enter image description here

How do you format the result, so it looks something like this:

0 Days, 0 Hours, 0 Minutes and 0.0968 Seconds

If it can intelligently show only values > 0, like these examples - it would be abonus:

Upvotes: 2

Views: 1780

Answers (1)

anubhava
anubhava

Reputation: 784918

You can use your last printf like this:

printf " >>> Process Completed - Total Runtime (d:h:m:s) : %d Days, %02d Hours, %02d Minutes, %02.4f Seconds\n" $dd $dh $dm $ds

However I would suggest you to use awk and do all calculations and formatting in awk itself so that you can avoid many invocations of bc.

Suggested awk script:

awk -v res1="$res1" -v res2="$res2" 'BEGIN {dt=res2-res1; dd=dt/86400; dt2=dt-86400*dd; 
      dh=dt2/3600; dt3=dt2-3600*dh; dm=dt3/60; ds=dt3-60*dm;
      printf " >>> Process Completed - Total Runtime (d:h:m:s) : %d Days, %02d Hours, %02d Minutes, %02.4f Seconds\n",
      dt/86400, dd, dh, dm, ds}'

Upvotes: 4

Related Questions