-1

I have a script where I keep time of when I start and finish. This code works on Linux, but not on my MacOS Sierra v 10.12.6

start=`date +"%a %b %d %Y %r"`
end=`date +"%a %b %d %Y %r"`
elapsed_time=`date -d @$(( $(date -d "$end" +%s) - $(date -d "$start" +%s) )) -u +'%H:%M:%S'`

The error I get is:

usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
        [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
        [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
-bash: - : syntax error: operand expected (error token is " ")

Is there a way to change this so that it works on my Mac?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
djl
  • 267
  • 1
  • 3
  • 13

2 Answers2

0
start=$(date +"%a %b %d %Y %r")
end=$(date +"%a %b %d %Y %r")
start_count=$(date -j -f "%a %b %d %Y %r" "$start" +%s)
end_count=$(date -j -f "%a %b %d %Y %r" "$end" +%s)
elapsed_time=$(date -u -r $(( $end_count - $start_count )) '+%H:%M:%S')
echo "$elapsed_time"

hope it helps

chepner
  • 497,756
  • 71
  • 530
  • 681
Lino
  • 5,084
  • 3
  • 21
  • 39
0

Just use seconds in the first place:

start=$(date +"%s")
// code to measure 
  end=$(date +"%s")
delta=$(date -d "@$((end-start))" -u +'%H:%M:%S')
echo $delta

If you like to produce formatted end and start times, too, it is more easy to go from %s to "%a %b %d %Y %r" and '%H:%M:%S' than the other way round. And avoid the outdated backticks. Use $(...) consistently, the can be wrapped around each other nicely.

user unknown
  • 35,537
  • 11
  • 75
  • 121