The ordering of operations wasn't what was causing the problem. According to this reference, the Korn shell has the same precedence and associativity as the C
programming language, so multiplication, division and remainder happen from left to right. The correct maths would be:
#!/bin/ksh
total_secs=3685
hour=$(( total_secs / 3600 ))
minute=$(( total_secs / 60 % 60 )) # equivalent to (total_secs / 60) % 60
seconds=$(( total_secs % 60 ))
echo "$hour:$minute:$seconds"
# output 1:1:25
If you want to format the output, perhaps you could use printf
printf "%02d:%02d:%02d\n" $hour $minute $seconds
# output 01:01:25
edit: operator precedence
Basic arithmetic operations are carried out in the following order:
*
/
%
+
-
Multiple operations of the same precedence will be evaluated from left to right as they appear in the expression.
$(( ((x*y) / z) + n ))
is equivalent to either of the following:
$(( x * y / z + n ))
$(( n + x * y / z ))
because in both cases, the *
is the highest precedence and nearest to the left of the expression. Second will be the /
and finally the +
.
There is no harm in inserting additional ( )
to make your intentions clear but remember that the whole expression must be enclosed within $(( ))
.