61

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

DeltaLima
  • 713
  • 5
  • 8
  • 3
    Psst: printf "%03d\n" 10 is completely usable in bash to obtain a leading zero for filenames and such. – Squeezy Jan 08 '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 08 '15 at 19:34
  • 8
    Note that you could've figured this out yourself just by doing echo $((016)) – user541686 Jan 09 '15 at 19:59
  • 2
    FYI, this is true in many programming languages: C, C++, Javascript. – Paul Draper Jan 11 '15 at 23:45

2 Answers2

128

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
Hauke Laging
  • 90,279
  • 23
    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
42

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.

fredtantini
  • 4,233