Bash Arithmetic – Fixing Math Failures with Leading Zero in Bash Double Paren

arithmeticbashshell

I have a simple script that deals with hours and minutes.

If I want to calculate number of minutes since midnight having a string s hh:mm I tried splitting string then doing hh * 60 + mm

My problem is, while

$ (( tot = 12 * 60 + 30 ))
$ echo $tot
750

instead

$ (( tot = 09 * 60 + 30 ))
bash: ((: tot = 09: value too great for base (error token is "09")

As far as I understand string 09 is not to be intended as a base 10 number.

Is there a better way than simply removing leading zeros in string?

Best Answer

h=09; m=30;(( tot = 10#$h * 60 + 10#$m )); echo $tot  

The number before the # is the radix (or base)
The number after the # must be valid for the radix
The output is always decimal
You can use a radix of 2 thru 64 (in GNU bash 4.1.5)

As noted by enzoyib, the old alternative of $[expression] is depricated, so it is beter to use the POSIX compliant $((expr))

$(( 2#1)) ==  1
$((16#F)) == 15
$((36#Z)) == 35  

I'm not sure which 'digits' are used after Z