1

Suppose I have the following code

for n in {50..300};
do
(( a = 0.3*$n))
#do something
echo $n
echo $a
done

when I run the code, I received an error, it says ((: a = 0.3*50: syntax error: invalid arithmetic operator (error token is ".3*50") I know it must be because 0.3 or any decimal number isn't recognizable or perhaps due to some formatting issues, as I previously tried ((a = $n / 2)) which worked fine, much appreciated if anyone can give me a hint.

1

1 Answer 1

1

While this is quite a trivial syntax issue, using shellcheck.net to debug such errors would have been much efficient. Your error line needs to be something like

a=$(echo "0.3*$n" | bc )        # 'echo' to print an arithmetic expression
                              # feeding it to 'bc' for the actual computation.
Sign up to request clarification or add additional context in comments.

7 Comments

@GavyLittlewolf: See ss64.com/bash/expr.html for what expr does.
there is an error when I tried to compile, it says a: command not found does that mean I need to declare the variable a? but I thought in bash script we do not need to?
Please paste your script in shellcheck.net and fix the errors seen, thereby making an attempt for yourself.
expr is the wrong command here; if bash could do floating-point arithmetic, you wouldn't need bc in the first place. It would seem to work since you didn't quote the argument; the expansion of 0.3*$n didn't match any files (* makes it a glob pattern), so was passed literally to expr, which treated it as a single non-numeric argument and simply spit it back out. I've edited the answer to use echo to simply feed a valid expression to bc.
It's also not a syntax issue; (( a = 5*$n )) would work fine as long as $n expands to an integer expression.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.