问题
In DOS/Batch,
if 08 lss 1 echo true
echoes "true". The same applies to 09. Both 08 and 09 are less than 1.
However,
if 07 lss 1 echo true
does not echo anything. 01 to 07 are not less than 1.
Why? What is special about 08 and 09?
回答1:
Typically, a leading 0
indicates you'd like the number to be parsed in octal. I'd expect 08
or 09
to actually be an error condition; perhaps the batch language does not have a good mechanism to signify that the input was incorrect?
回答2:
Extending the answers that sarnold and David Schwartz already provided...
I've never seen any documentation that states that IF supports octal or hexadecimal numeric notation. But your question prompted me to do some tests, and indeed it does support the same numeric notation that SET /A supports.
- Any set of digits [0-9] not starting with 0 is interpreted as decimal.
- Any set of digits [0-7] prefixed with 0 is interpreted as octal.
- Any set of digits [0-9,A-F,a-f] prefixed with 0x or 0X is interpreted as hexadecimal.
Any set of characters that does not satisfy any of the 3 numeric notations above is treated as a string.
If both sides of the comparison are valid numbers, then a numeric comparison is made.
If either side is not a valid number, then a string comparison is made.
07 is a valid octal notation with decimal value of 7, and it is not less than 1.
08 and 09 are prefixed with 0 but are not valid octal notation, so a string comparison is made. Any string starting with 0 will sort as less than a string starting with 1.
Some interesting tests to confirm that octal and hexadecimal notation are supported.
if 0xA equ 10 echo ok
if 011 equ 9 echo ok
It is mildly interesting that invalid octal or hexadecimal notation in a SET /A statement raises an error. But invalid octal or hexadecimal notation in an IF statement does not raise an error. It simply forces a string comparison.
Update
A valid number may be preceded with a sign indicator: - or +
if +0xA equ +10 echo ok
if -011 equ -9 echo ok
回答3:
08 and 09 are illegal. In octal, 7 is the highest legal digit. A lead digit of zero signifies a number represented as octal.
来源:https://stackoverflow.com/questions/10628700/08-is-less-than-1-but-07-is-greater-than-1-in-dos-batch-why