Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash arithmetic expansion behaviour with empty variables

Tags:

bash

I have trouble understanding how bash arithmetic expansion works in some specific cases:

  • variable is unset or empty
  • operation involves another operator than + or -
  • a dollar is used to expand variable

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?

like image 398
Quentin L'Hours Avatar asked Oct 25 '25 15:10

Quentin L'Hours


1 Answers

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.

like image 143
Benjamin W. Avatar answered Oct 27 '25 11:10

Benjamin W.