views:

58

answers:

5

I've got some issues on scripting... if someone could help me, it would be really good !

My script has:

VISITS=$((WR + RD));
SERVICE_DEMAND=$((VISITS*SERVICE_DEMAND));

And I'm getting this error:

./calc_serv_demand.sh: line 12: 0.0895406: syntax error: invalid arithmetic operator (error token is ".0895406")

Can someone help me?

I think it's because the bash works only with integer... I need to use float values, though.

thanks in advance


Problem solved:

VISITS=$(echo $WR + $RD | bc); echo $VISITS

SERVICE_DEMAND=$(echo $VISITS '*' $SERVICE_TIME | bc); echo $SERVICE_DEMAND

+2  A: 

Use bc to do float calculations in Bash.

Sjoerd
+5  A: 

You can use bc to do your floating point calculations, i.e.

echo $WR + $RD | bc

and so on.

honk
HUm...it works for the sum, it doesn't work well for the multiplication. It's weird because I've checked on bc manual and it should work !Have a look:My script:echo $WR + $RD | bc VISITS=$(echo $WR + $RD | bc); # works fineecho $VISITSSERVICE_DEMAND=$(echo $VISITS * $SERVICE_TIME | bc); # return a weird errorecho $SERVICE_DEMANDError:0.08954063.4200712.4013.5096106(standard_in) 1: syntax error(standard_in) 1: illegal character: K(standard_in) 1: illegal character: H(standard_in) 1: illegal character: T...
Alucard
@user: Since `*` has a special meaning for the shell you have to write either `\\*` or `'*'`.Also, you should directly assign the result of the calculation to a variable instead of outputting to file: `VISITS=$(echo $WR + $RD | bc)`.
honk
@user368453: If you do an `echo` of an `*` it displays all the filenames in the current directory. Just put quotes around the formula and it will work: `SERVICE_DEMAND=$(echo "$VISITS * $SERVICE_DEMAND" | bc)`
Dennis Williamson
Great!! Now it works !!Thanks everyone ...
Alucard
quote your variables and you should be fine. `echo "$WR+$RD" | bc`
ghostdog74
+1  A: 

You'll have to use an external program like bc to do floating-point math in your scripts.

Something like:

echo ($WR+$RD)*$SERVICE_DEMAND | bc

chocolate_jesus
+2  A: 

To set the precision (number of digits of the answer to the right of the decimal point), write:

WR=5
RD=7
VISITS=$[WR+RD]
SERVICE_DEMAND=.0895406
SERVICE_DEMAND=`echo "scale=5; $VISITS * $SERVICE_DEMAND" |bc -l`
echo Service Demand = $SERVICE_DEMAND

This outputs:

Service Demand = 1.0744872

The scale=5 sets 5 digits of precision; the backquotes cause the contained expression to be evaluated and the ouput (from the bc -l) to be assigned to your variable.

Larry Morell
ThanksBut...It returned the following mistake:(standard_in) 2: syntax error
Alucard
A: 

Instead of using bc, consider switching to a better programming language. Bash is simply unsuited for mathematics.

Philipp