That's an extension of
bash (and also
ksh and its derivatives) to allow shell variable contain invalid integer constant to be reused in arithmetic expression.
bash Shell Arithmetic:
Shell variables are allowed as operands; parameter expansion is
performed before the expression is evaluated. Within an expression,
shell variables may also be referenced by name without using the
parameter expansion syntax. A shell variable that is null or unset
evaluates to 0 when referenced by name without using the parameter
expansion syntax. The value of a variable is evaluated as an
arithmetic expression when it is referenced, or when a variable which
has been given the integer attribute using ‘declare -i’ is assigned a
value. A null value evaluates to 0. A shell variable need not have its
integer attribute turned on to be used in an expression.
So in your case,
$((x)) first expanded
foo, which is an invalid integer, so
foo is reused as a variable name reference. Then
foo was expanded to
bar, the process above was repeated, until you got
6, which is an valid integer.
POSIX spec only stated that
$(($x)) will return the same value only when
x is a valid integer constant. It does not say anything about the case
x is an invalid integer, so shell implementations is free to handle this situation.
The result can be varied with different shells.
ksh and its derivatives behave like
bash above (and also busybox
dash raise error if
x contain invalid integer
$ x=foo foo=bar bar=6 dash -c 'echo "$((x))"'
dash: 1: Illegal number: foo
yash leaves the variable as-is:
$ x=foo foo=bar bar=6 yash -c 'echo "$((x))"'