Expression recursion level exceeded

匆匆过客 提交于 2019-12-22 09:03:21

问题


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")
n

回答1:


$ 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 RHS 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.



回答2:


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.



来源:https://stackoverflow.com/questions/30404863/expression-recursion-level-exceeded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!