I have a fixed length string which is a number. When I assign the string to a variable it is getting assigned 8 instead of 10. Why? How do I stop it?
$ i=10
$ ((i=i+1))
$ echo $i
11 # Right answer
$ i=000010
$ ((i=i+1))
$ echo $i
9 # Wrong answer
Update: The answers confirm that the number is being converted to octal and that the leading zeros need to be removed. Here is the sed
command for that.
echo "000010" | sed 's/0*//'
That's because a leading
0
means that the constant is octal (base 8) instead of decimal (base 10). To stop it, you need to strip off the leading 0sKorn shell interprets numbers starting with zero as octal.
A leading zero on a number (in C, C++, C# et al) means "this is an octal constant" and (oct) 10 == (dec) 8.
This will strip leading zeros without resorting to spawning
sed
(at least in ksh93):The same thing works in Bash if you have extended globbing turned on (
shopt -s extglob
).Edit:
You can also force the value to be interpreted as base-10:
What you write here:
cannot be true. Interpretation of numeric literals only takes place inside arithmetic expansion (i.e. double parens). Otherwise
0888
is just an ordinary string and if shell would strip the leading zero or convert the number to some other base it would be an awful bug. Just checked in the Korn shell: