Can somebody explain to me why a number with a leading 0 gives this funny behaviour?
#!/bin/bash
NUM=016
SUM=$((NUM + 1))
echo "$NUM + 1 = $SUM"
Will print:
016 + 1 = 15
The misunderstanding is that the numbers don't mean what you expect.
A leading zero denotes a number with base 8. I.e. 016
is the same as 8#16
. If you want to keep the leading zero then you need 10#016
.
> num=016
> echo $((num))
14
> echo $((10#$num))
16
Because:
~$ echo $((NUM))
14
if the number begins with 0, it is considered to be an octal value and 16 in octal is 14 in decimal.
printf "%03d\n" 10
is completely usable in bash to obtain a leading zero for filenames and such. – Squeezy Jan 08 '15 at 19:15echo $((016))
– user541686 Jan 09 '15 at 19:59