Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

bash

math

bc

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.

like image 214
NoBugsOnlyFeatures Avatar asked Feb 06 '26 12:02

NoBugsOnlyFeatures


2 Answers

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)")"
like image 116
anubhava Avatar answered Feb 09 '26 05:02

anubhava


Better do it like below. It would be more clear

result=$(bc -l <<< ($sum / $total))
printf "%.3f\n" "$result"
like image 35
Abhijit Pritam Dutta Avatar answered Feb 09 '26 03:02

Abhijit Pritam Dutta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!