As far as I had known, [[
and [
can be expected to behave mostly the same, taking into account a few extra features [[
has. But recently I noticed a discrepancy in how bash treats octal expansions:
$ b=010; echo $((b))
8
$ [[ $b -eq 8 ]]; echo $?
0
but
$ [ $b -eq 8 ]; echo $?
1
$ test $b -eq 8; echo $?
1
$ [ $b -eq 10 ]; echo $?
0
Why does the latter expression drop the auto octal conversion? Expressions like -eq
are "Arithmetic" according to help test
in Bash and the Bash Reference Manual, and further according to the next section of the reference manual constants with a leading zero can be treated as octal.
POSIX sh is a little less clear on the subject: Even though POSIX arithmetic expressions still expand leading-zero integers to their octal value, it refers to -eq
expressions in test
as algebraic, not arithmetic.
Is there any documentation or evidence to suggest that bash makes a distinction between [[
and [
for octal expansion on purpose, or is it just an accidental feature?
[[ is known as the extended test command and behaves as ksh88, you can find an elaboration here: http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS
Also if you need to be sure of the base in bash you can use the # base operator like this:
b=010; echo $((10#$b))
10
b=10; echo $((8#$b)
8
b=013; echo $((8#$b))
11