I have some bash issues:
This is expected:
[[ 0 -eq 0 ]] && echo "equal!"
> equal!
This is not:
[[ "" -eq 0 ]] && echo "equal!"
> equal!
Why is ""
equal to 0
?
How can I check for numeric equality?
I have some bash issues:
This is expected:
[[ 0 -eq 0 ]] && echo "equal!"
> equal!
This is not:
[[ "" -eq 0 ]] && echo "equal!"
> equal!
Why is ""
equal to 0
?
How can I check for numeric equality?
This is because Bash tries hard to convert whatever you put into both sides of -eq
into integers, and will convert the empty string to zero. The conversions are far from trivial. Here's how I expect the code parses numbers, without actually having read it:
$ [[ x -eq 0 ]] && echo "equal!"
equal!
After Bash detects a numeric context (-eq
) it starts creating a number from zero on the left side, scans and finds x, discards it, scans and finds whitespace, and therefore considers the left side zero. Hence the above is equivalent to [[ 0 -eq 0 ]]
$ [[ 0x10 -eq 16 ]] && echo "equal!"
equal!
Starting from zero again, Bash sees a zero (before the "x") and goes into "alternate base" mode, finds an "x" and goes into hexadecimal mode, and reads the remaining digits ("10") as a hexadecimal number.
$ [[ 00x10 -eq 16 ]] && echo "equal!"
bash: [[: 00x10: value too great for base (error token is "00x10")
After going into "alternate base" mode after seeing a zero Bash sees a number (the second zero), and therefore goes into octal mode. x
is considered a "numeric character" in this mode because it can be used in higher bases, but "x" is not a valid octal digit, so it fails.
See the Bash manual for more.