开发者

KornShell: Variable assigned "000010" converted to 8 instead of 10.

开发者 https://www.devze.com 2023-01-06 10:12 出处:网络
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 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 开发者_JAVA技巧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 0s


Korn 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):

$ i=000010
$ i=${i/#*(0)}
$ ((i++))
$ echo $i
11

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:

$ i=000010
$ ((i = 10#$i + 1))
$ echo $i
11


What you write here:

$ i="0888"   # 888 with a leading zero.
$ echo ${i}
888          # Is fine.

$ i="000010"
$ echo ${i}
8            # This returns 8 however.

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:

$ i="0888"
$ echo ${i}
0888
$ i="000010"
$ echo ${i}
000010

$ ksh --version
  version         sh (AT&T Research) 93s+ 2008-01-31
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号