加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash中的表达式递归级别超出了错误

发布时间:2020-12-15 21:39:36 所属栏目:安全 来源:网络整理
导读:我是打击脚本并试图做一些练习的新手.当我试图用“完成”字符串停止程序时,得到这样的错误: line 9: ((: finish: expression recursion level exceeded (error token is "finish"). 问题是什么?我还想了解其他的错误. 我的计划是: #!/bin/bashnumber=0fin
我是打击脚本并试图做一些练习的新手.当我试图用“完成”字符串停止程序时,得到这样的错误:

line 9: ((: finish: expression recursion level exceeded (error token is "finish").

问题是什么?我还想了解其他的错误.
我的计划是:

#!/bin/bash
number=0
finish="finish"
temp=0
echo "Enter a number."
while true;
do
    read -r number
    if (( $number > $temp ))
    then
        temp=$number
    fi
    if [[ $number == $finish ]]
    then 
       break
    fi
done    
echo "Largest : $temp"

解决方法

从 @barmar’s great answer引用相关问题,该问题讨论了@GordonDavisson在评论中提到的同一问题:

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 $finish,and this keeps
repeating infinitely.

最简单的解决方案是为变量使用不同的名称 – 比如finish_string =“finish”而不是finish =“finish”.

此外,您可以使用正则表达式匹配来查看值是否为数字(注意:在算术表达式((…)中)扩展变量不需要美元符号),然后执行数字比较,然后进行正常的字符串比较查看值是否为“完成”:

if [[ $number =~ ^[0-9]+$]] && ((number > temp)); then
  temp=$number
elif [[ $number == $finish ]]; then
  break
fi

或者,您可以在进行数字比较之前明确检查用户是否输入了数字:

if [[ $number == $finish ]]; then
  break
else
  [[ $number =~ ^[0-9]+$]] || { echo "Enter a valid number or 'finish' to stop"; continue; }
  if ((number > temp)); then
    temp=$number
  fi
fi

使用bash -x yourscript.sh运行脚本进行调试.

有关:

> Expression recursion level exceeded

也可以看看:

> How to use double or single brackets,parentheses,curly braces

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读