18

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)?

4
  • 17
    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
    Commented May 9, 2015 at 13:24
  • 3
    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. Commented May 9, 2015 at 14:44
  • 9
    This is actually an important thing to know when programming. In most languages 0 triggers octal, 0x hex and 0b binary.
    – Seth
    Commented May 10, 2015 at 1:47
  • 3
    @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
    Commented May 10, 2015 at 17:03

1 Answer 1

43

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
4
  • Edited the question with two ways to solve it.
    – Pabi
    Commented May 9, 2015 at 13:24
  • 1
    @Tim to do that you can use ${N%?} to chop the last digit and then ${N:-} to replace blank with 0.
    – Random832
    Commented May 9, 2015 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
    Commented May 9, 2015 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
    Commented May 9, 2015 at 19:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .