Search code examples
bashexpressionparenthesesoperator-precedence

Bash addition before multiplication (precedence in expression using parenthesis)


I'm trying to sum 1 to a variable before multiplying the result In Java it's something like

int upperBound = (curBatch + 1) * elePerBatch;

I've tried the following

upperBound=$(($curBatch + 1 * $elePerBatch))
upperBound=$((($curBatch + 1) * $elePerBatch))
upperBound=$(((($curBatch + 1)) * $elePerBatch))
upperBound=$(($(($curBatch + 1)) * $elePerBatch))

Nothing works, and I get this kind of error

0 + 1 * : syntax error: operand expected (error token is "* ")

I've seen this error in other questions, but I found no solution to my problem.


Solution

  • Turns out elePerBatch was not initialized.

    I couldn't figure out what the error meant, otherwise I would have noticed it.

    This works

    upperBound=$(($(($curBatch + 1)) * $elePerBatch))