Ubuntu – How to subtract float values in shell script

bashcommand linescripts

I have a script which uses float values but some how i am not able to subtract two floats.

This is the sample code

#!/bin/bash

p="1"
h="10"
m=$(echo "3.5"| bc -l)
for (( c=$p; c<=$h; c++ ))
do
   r=$(echo "($p-$m)"| bc -l)

   echo "Z $c $m $r"
done

and this is the result

Z 1 3.5 -2.5
Z 2 3.5 -2.5
Z 3 3.5 -2.5
Z 4 3.5 -2.5
Z 5 3.5 -2.5
Z 6 3.5 -2.5
Z 7 3.5 -2.5
Z 8 3.5 -2.5
Z 9 3.5 -2.5
Z 10 3.5 -2.5

Best Answer

Change the line

   r=$(echo "($p-$m)"| bc -l)

to

   r=$(echo "($c-$m)"| bc -l)

as it isn't $p but $c that is changed by the loop.

Related Question