# Why does bash think: 016 + 1 = 15?

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

• Psst: `printf "%03d\n" 10` is completely usable in bash to obtain a leading zero for filenames and such. – Squeezy Jan 8 '15 at 19:15
• @Squeezy Thanks, but that part was already working. The actual problem was not obtaining a filename with a leading 0. It was finding out what the filename was with the highest number and then creating the next-in-sequence, by using printf "prefix-%03d.tif" \$SUM. – DeltaLima Jan 8 '15 at 19:34
• Note that you could've figured this out yourself just by doing `echo \$((016))` – Mehrdad Jan 9 '15 at 19:59
• FYI, this is true in many programming languages: C, C++, Javascript. – Paul Draper Jan 11 '15 at 23:45

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
``````
• There are 10 types of people in the world. Those who understand binary, those who don't, those who weren't expecting a base 8 joke, and 5 other types of people. – Jon Story Jan 12 '15 at 13:36

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.

• That makes perfectly sence and explains why my script was overwriting my old files :-( – DeltaLima Jan 8 '15 at 15:33