Search code examples
bashmathsyntaxbc

Why am I getting a syntax error in this bash command on parentheses printf and calculator function?


Why am I getting an error with the ( in this line of script?

printf "%.3f\n" "$(bc -l <<< ($sum / $total))"

Error:

solution.sh: command substitution: line 11: syntax error near unexpected token `('
solution.sh: command substitution: line 11: `bc -l <<< ($sum / $total))"'

The desired behavior is to take a numerical variables $sum and $total and perform division on them, then print out the value to 3 decimal points.


Solution

  • It is because bc -l needs input as a single string but ($sum / $total) is unquoted and gets split into more than one word.

    You may use:

    printf "%.3f\n" "$(bc -l <<< "($sum / $total)")"