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.
精彩评论