4

I have been doing integer calculation like this.

a=12
b=23
c=$((a-b))
echo $c

But, now for float numbers its is failing i read that we can do that using bc however i want to assign the result in variable at the end.

a=12.7
b=23.33
c=$((a-b)) | bc
echo $c
perror
  • 3,239
  • 7
  • 33
  • 45

1 Answers1

5
c=$( printf '%s - %s\n' "$a" "$b" | bc )

or, for the lazy,

c=$( echo "$a - $b" | bc )

or, for the lazy bash user,

c=$( bc <<<"$a - $b" )

The issue with your code is that

c=$((a-b)) | bc

won't work. You can only (usefully) pipe things that produces output, and c=$((a-b)) is an assignment that 1) will fail if $a or $b are floating point numbers (with a syntax error), and 2) does not produce output. Furthermore, the output from bc (nothing) will not be assigned to c since it's not part of the assignment at all.

Kusalananda
  • 333,661