# Why does bash thinks that 010 is 8?

Why does bash think the number 010 = 8?

``````x=010
echo \$x
010
echo \$(( x+0 ))
8
echo \$(( x-2 ))
6
``````

I thought it might be binary, but 010 = 10 = 2. So why does it get 8, and how can I make it think 010 = 10 (and 010 - 2 = 8)?

• The leading `0` tells it to be octal. If you just do `x=10` then `echo \$((x+0))` then shows `10`. Also, there is no need for the extra `\$` with in the `()`. – Terrance May 9 '15 at 13:24
• In many number parsers, `010` means 8 because by putting a `0` in front means octal, similar to how putting `0x` in some languages means hex. – Derek 朕會功夫 May 9 '15 at 14:44
• This is actually an important thing to know when programming. In most languages `0` triggers octal, `0x` hex and `0b` binary. – Seth May 10 '15 at 1:47
• Downvote explanations? – Tim May 10 '15 at 17:01
• @tim why would it -not- be 8? ;-) Oh not my downvote though but probably because it is too basic. It is pretty normal behaviour. – Rinzwind May 10 '15 at 17:03

Number sequences starting with a `0` are interpreted as octal numbers.
Octal `10` = decimal `8`.

To get bash to treat it as a decimal number, remove the leading zero or force decimal with:

``````N=010
N=\$((10#\$N))
``````

Generally that works for all bases, just replace the `10` with the base that you want:

``````N=[base#]n
``````
• Edited the question with two ways to solve it. – Pabi May 9 '15 at 13:24
• @Tim to do that you can use \${N%?} to chop the last digit and then \${N:-} to replace blank with 0. – Random832 May 9 '15 at 17:27
• @Tim if so I couldn't figure out how. \${\${N%?}:-0} works in zsh but not in bash or ksh. (Also, `:-` in my comment above should have been `:-0`} – Random832 May 9 '15 at 18:02
• You should include in your answer that you can force any base with the "form [base#]n, where base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base" source: bash ref – djeikyb May 9 '15 at 19:27