0

Lets say I have below two variables.

!#/bin/bash
MEMFILE=lock-file
date +%s > $MEMFILE
sleep 130
UPTIME= `date +%s`

I want to take the output of ( $UPTIME - $MEMFILE) in minutes and seconds.

Eg:

 "Total downtime was 2 minutes and 5 seconds"
dogbane
  • 266,786
  • 75
  • 396
  • 414
hlesnt395
  • 603
  • 10
  • 30
  • All these came at single line. i'm sorry. I didnt know how it can be code properly in this forum. since i'm new. – hlesnt395 Jun 18 '16 at 11:37
  • You should indent the code with 4 leading spaces in the line. Also, have a look at http://stackoverflow.com/help/mcve – Vinicius Placco Jun 18 '16 at 11:40
  • http://stackoverflow.com/questions/8903239/how-to-calculate-time-difference-in-bash-script Seen this? – Athanasios Kataras Jun 18 '16 at 11:49
  • 1
    I don't know that you really want to do ([you want to do X, you think that to do X you need Y, so you ask a question about Y](http://mywiki.wooledge.org/XyProblem)), but using the `SECONDS` variable might help you: `SECONDS=0; sleep 130; uptime=$SECONDS; echo "Total downtime was $((uptime/60)) minutes and $((uptime%60)) seconds"`. The `SECONDS=0` line is to reset the `SECONDS` counter: it's then incremented by one every second. See [what the manual says about `SECONDS`](https://www.gnu.org/software/bash/manual/bashref.html#index-SECONDS). – gniourf_gniourf Jun 18 '16 at 11:54
  • @gniourf_gniourf, you should post that as the answer. – glenn jackman Jun 18 '16 at 12:27

1 Answers1

0

Several possibilities:


Subtracting times obtained from date:

#!/bin/bash

startdate=$(date +%s)
sleep 130
enddate=$(date +%s)
timetaken=$((enddate-startdate))
printf 'Total downtime was %d minutes and %d seconds\n' "$((timetaken/60))" "$((timetaken%60))"

The same without the external process date (since Bash 4.2):

#!/bin/bash

printf -v startdate '%(%s)T' -1
sleep 130
printf -v enddate '%(%s)T' -1
timetaken=$((enddate-startdate))
printf 'Total downtime was %d minutes and %d seconds\n' "$((timetaken/60))" "$((timetaken%60))"

The subtraction of times and computing the minutes and seconds are done using arithmetic expansion.


Using Bash's SECONDS variable (probably the best for you):

#!/bin/bash

SECONDS=0 # reset the SECONDS variable
sleep 130
timetaken=$SECONDS
printf 'Total downtime was %d minutes and %d seconds\n' "$((timetaken/60))" "$((timetaken%60))"

After being set to an integer value the special variable SECONDS is incremented each second.


Using Bash's time keyword with an appropriate TIMEFORMAT (here, we won't be able to write the elapsed time as MM minutes and SS seconds; it'll be shown in the form of MmSs, i.e., Total downtime was 2m10s).

#!/bin/bash

TIMEFORMAT='Total downtime was %0lR'

time {
    # do your stuff in this block
    sleep 130
}

Note that the linked answer already contains a lot of material.

Community
  • 1
  • 1
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104