5

Don't know why there is error in the following examples:

$ a=1; (( a > 0 )) && echo y || echo n
 y
$ a=x; (( a > 0 )) && echo y || echo n
 n
$ a=a; (( a > 0 )) && echo y || echo n
 -bash: ((: a: expression recursion level exceeded (error token is "a")
Tms91
  • 3,456
  • 6
  • 40
  • 74
user2847598
  • 1,247
  • 1
  • 14
  • 25

2 Answers2

10
$ a=a
( no error )
$ declare -i a
$ a=a
-bash: ((: a: expression recursion level exceeded (error token is "a")

This behavior is because declare -i puts the right-hand side of an assignment in arithmetic context. In arithmetic context, bash dereferences variable names to their values recursively. If the name dereferences to itself, infinite recursion ensues.

To clarify further, you would only get this behavior if the variable in question was assigned to a string identical to the name of the variable before setting the integer attribute on that name.

$ unset a
$ declare -i a
$ a=a
( This is fine, $a dereferences to 0. )
$ unset a
$ a=a
$ declare -i a
$ a=a
-bash: ((: a: expression recursion level exceeded (error token is "a")

That's why this is a rare occurrence. If you do the assignment when you're already in arithmetic context, then the right-hand side cannot resolve to anything other than an integer. No recursion can occur. So either

  1. Do everything inside (( )). (You can do assignments in there, too.)
  2. Use declare -i first thing; don't mix types.
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • 1
    One “funny” case where you can get that error is this: Forget to declare an associative array, and then try to use that array. Bash will interpret this as an attempt at using an _indexed_ array rather than an _associative_ one, and will put you in an arithmetic context for the index. Therefore, `foo=foo; result=${not_declared[$foo]}` produces the error, while `declare -A declared; foo=foo; result=${declared[$foo]}` works fine. The error message can be a bit misleading in such cases! – Alice M. May 26 '23 at 16:34
7

When you use a variable in an arithmetic expression, but the value is not a number, the shell treats it as another expression to evaluate. So if the value is a variable name, it will get the value of that variable and use it. But in this case, you have it pointing to itself. So to evaluate a it has to evaluate a, and this keeps repeating infinitely.

Barmar
  • 741,623
  • 53
  • 500
  • 612