3

Infact when i want to have an estimated time it took when a script is finished.

startdate=$date

stuffs

enddate=$date

I wished to get the difference between these two dates and normally the script finishes less than 1 week. So i'll need it in number of days & minutes.

Kusalananda
  • 333,661

4 Answers4

10

From the bash manual:

SECONDS

Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

So whenever you want to time a piece of code with a timer that counts seconds, you may do

SECONDS=0

# code goes here

t=$SECONDS

To print days and minutes from the $t value:

printf 'Time taken: %d days, %d minutes\n' "$(( t/86400 ))" "$(( t/60 - 1440*(t/86400) ))"
Kusalananda
  • 333,661
  • Hi, I confirm this one working. Many thanks – Keshav Boodhun May 29 '20 at 05:01
  • @KeshavBoodhun Good! You may want to look at https://unix.stackexchange.com/help/someone-answers, and also take the tour: https://unix.stackexchange.com/tour (you'll receive a badge when you've done so). – Kusalananda May 29 '20 at 05:39
1

Additionally: time bash script.sh

glenn jackman
  • 85,964
0

You can use timestamps with date "+%s"

$ date "+%s"
1590502845

And use bash $(()) for the calculation

START=$(date "+%s")

work ... work... work ...

END=$(date "+%s")

echo $((END-START))
Rabin
  • 3,883
  • 1
  • 22
  • 23
0

What's missing from most answers, is a simple way to get the time in terms of hh:mm:ss format.

Let's keep things simple, and use Bash built-ins only:

# Using the Bash built-in SECONDS
SECONDS=0;sleep 0; t=$((SECONDS+241));TT=$(date -u -d "@${t}" +%T); printf 'Time taken: %s\n' "$TT"
# Time taken: 00:04:01

Using date differences, and give result in hh:mm:ss

S=$(date -u +"%s"); E=$((S+121)); TT=$((E-S)); date -u -d "@${TT}" +%T

00:02:01

not2qubit
  • 1,666