1

I have below code to calculate the time difference in mm:ss format. However its not working if I have values like 08/09. I saw in few blobs by adding #10 it will resolve , however its not working out for me. can anyone please help .

#!/bin/bash
start_ts=04:24:07
stop_ts=04:24:09
ts_get_sec()
{
  read -r h m s <<< $(echo 10#$1 | tr ':' ' ' )
  echo $(((h*60*60)+(m*60)+s))
}
START=$(ts_get_sec $start_ts)
STOP=$(ts_get_sec $stop_ts)
DIFF=$((STOP-START))
echo "$((DIFF/60)):$((DIFF%60))"

Error I am getting:

value too great for base (error token is "09")

Please suggest if syntactically I am correct or not.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
John
  • 23
  • 6
  • Can you show the example with problems? You should add `10#` inside `$(( ))` like change `$((h * 60))` into `$((10#$h * 60))`. – KamilCuk Mar 12 '19 at 12:24

2 Answers2

1

This doesn't work because 09 is great in octal base.

$(echo 10#$1 | tr ':' ' ')

will result in: 10#04 24 09, so only 04 is considered a decimal number, while 09 is considered octal number.

Try this:

$(echo $1 | awk -F ":" '{ print "10#" $1 " 10#" $2 " 10#" $3; }' )

that is: 10#04 10#24 10#09 so every number is decimal number and it should fix the error.

Lety
  • 2,511
  • 21
  • 25
0

Remove leading blanks from h m, and s after the split:

ts_get_sec()
{
  read -r h m s <<< $(echo $1 | tr ':' ' ' )
  h=$((10#$h))
  m=$((10#$m))
  s=$((10#$s))  
  echo $(((h*60*60)+(m*60)+s*1))
}
monok
  • 494
  • 5
  • 16