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)?
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
:- in my comment above should have been :-0}
Commented
May 9, 2015 at 18:02
0tells it to be octal. If you just dox=10thenecho $((x+0))then shows10. Also, there is no need for the extra$with in the().010means 8 because by putting a0in front means octal, similar to how putting0xin some languages means hex.0triggers octal,0xhex and0bbinary.