Where does the recursive variable expansion in bash/shell numeric contexts come from? Where does the recursive variable expansion in bash/shell numeric contexts come from? bash bash

Where does the recursive variable expansion in bash/shell numeric contexts come from?


It's worse than you think. The value of the variable is recursively treated as an arithmetic expression:

$ foo='bar+bar'$ echo $((foo))10

The bash manual section on Shell Arithmetic says:

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.

The latter part means you can do:

$ declare -i int$ int=bar+bar$ echo $int10

Note that none of this is a violation of the spec you quoted above. It only says what should be done if the value of the variable is an integer constant. It doesn't say what should be done if the value is something else, which leaves that open for implementations to add extensions like this. Bash Hackers Wiki explains it:

If the variable doesn't hold a value that looks like a valid expression (numbers or operations), the expression is re-used to reference, for example, the named parameters

If the eventual expansion is not a valid expression, you'll get an error:

$ foo='a b'$ bar=fooecho $((bar))bash: a b: syntax error in expression (error token is "b")

So if your variable contains random stuff, it's likely to cause an error. But if it just contains a single word, which is valid variable syntax, that will evaluate as 0 if the variable isn't set.