I have trouble understanding how bash arithmetic expansion works in some specific cases:
When all these requirements are met I get the error:
syntax error: operand expected (error token is ...
Here are some examples :
unset var # or var=''
unset value
echo $(($var * 2)) # error
echo $(($var + 2)) # no error
echo $((var * 2)) # no error
var='value'
echo $(($var * 2)) # no error
Why is var not replaced by a 0 in the first statement like in all the other ones?
Expansion of parameter names in arithmetic context has special properties. For example, parameter names are resolved until we find a numeric value:
$ var1=5
$ var2=var1
$ echo $(( var2 ))
5
If the chain ends, for example if var1 isn't defined in above example, the result is zero:
$ unset var1
$ echo $(( var2 ))
0
Using the parameter name directly also expands to zero:
$ echo $(( var1 ))
0
Even nothing expands to zero:
$ echo $(( ))
0
But there is a difference between using $var and just var:
$ unset var
$ echo $(( var * 1 ))
0
$ echo $(( $var * 1 ))
-bash: * 1 : syntax error: operand expected (error token is "* 1 ")
The first one expands to 0 * 1, but the second one to * 1, which is a syntax error because * requires two operands. This is your first example.
Your second example expands to + 2, which is fine: + is interpreted as unary plus. It's not replaced by a zero, as you assume in your question.
The third and fourth one both expand to 0 * 2, as shown above: non-integer values like value are interpreted as zero in arithmetic context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With