Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression recursion level exceeded error in Bash

Tags:

I'm a newbie to bash scripting and trying to do some exercises. Getting error like this when I'm trying to stop the program with "finish" string.:

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

What is the problem? Also I'd like to learn my other faults. My program is:

#!/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"  
like image 634
Cemil Çakmak Avatar asked Oct 11 '18 06:10

Cemil Çakmak


1 Answers

To quote from @barmar's great answer to the related question, which talks about the same issue that @GordonDavisson mentions in his comment:

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.


The simplest solution is to use a different name to your variable - say finish_string="finish" instead of finish="finish".

Also, you can use a regex match to see if the value is numeric (note: a dollar sign is not needed to expand variables inside arithmetic expression ((...))), then do the numeric comparison followed by the normal string comparison to see if the value is 'finish':

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

Or, you could explicitly check if the user entered a number before doing a numeric comparison:

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

Run your script with bash -x yourscript.sh to debug it.


Related:

  • Expression recursion level exceeded

See also:

  • How to use double or single brackets, parentheses, curly braces
like image 93
codeforester Avatar answered Nov 15 '22 11:11

codeforester