开发者

Error in Bash script arithmetic syntax

Script:

#!/bin/bash
vpct=5.3 
echo $((vpct*15))    

Error:

./abc.sh: line 5: 5.3: syntax error: invalid arithmetic operator (error开发者_如何学Python token is ".3")

I know I don't need a script to multiply 5.3 * 15, but this small script to single out the error. Please advise.


According to http://www.softpanorama.org/Scripting/Shellorama/arithmetic_expressions.shtml:

Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings.

You should use bc to perform such calculations, just as in dogbane's solution, except that you should escape the expression using quotes so the * character doesn't cause unwanted shell expansion.

echo "$vpct*15" | bc


Besides bc, there are other tools you can tools you can try

awk -v vpct="$VPCT" 'BEGIN{print vpct * 15}'

echo $vpct | ruby -e 'print gets.to_f * 15 '

echo  "$vpct 15 * p" | dc


You should use bc for floating point arithmetic:

echo "$vpct*15" | bc


$(( $vpct * 15 )) // (add a $ sign should do it)


Shebang should be written like #! And anyway $(()) is only for integers.


If you have ksh available, it will do float arithmetic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜