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"
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"
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.