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:
See also: