3

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.

Cyrus
  • 84,225
  • 14
  • 89
  • 153

2 Answers2

1

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)")"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • It is closer, though now it is throwing an error on standard in: (standard_in) 1: syntax error – NoBugsOnlyFeatures Apr 03 '18 at 18:57
  • Are you using `bash`? When I use `sum=15; total=25; printf "%.3f\n" "$(bc -l <<< "($sum / $total)")"` I get `0.600` – anubhava Apr 03 '18 at 19:06
  • Yes and no. This is part of a problem from Hackerrank. [Link to the problem](https://www.hackerrank.com/challenges/bash-tutorials---compute-the-average/problem) – NoBugsOnlyFeatures Apr 03 '18 at 20:08
  • 1
    Reading the discussion, I think it is a buggy problem set along with me mishandling reads. Not related to the problem. This works. – NoBugsOnlyFeatures Apr 03 '18 at 20:15
  • 1
    For the problem that you linked can be solved by using `sum=0; total=; while read num; do [[ -z $total ]] && total=$num || ((sum += num)); done < file; printf "%.3f\n" "$(bc -l <<< "($sum / $total)")"` – anubhava Apr 03 '18 at 20:16
1

Better do it like below. It would be more clear

result=$(bc -l <<< ($sum / $total))
printf "%.3f\n" "$result"
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17