Bash 脚本算术语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5040784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:12:01  来源:igfitidea点击:

Error in Bash script arithmetic syntax

bash

提问by Humble Debugger

Script:

脚本:

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

Error:

错误:

./abc.sh: line 5: 5.3: syntax error: invalid arithmetic operator (error 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.

我知道我不需要一个脚本来乘5.3 * 15,但是这个小脚本来挑出错误。请指教。

采纳答案by kurumi

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

此外bc,还有其他工具可以尝试

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

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

echo  "$vpct 15 * p" | dc

回答by SirDarius

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

根据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.

Bash 不了解浮点运算。它将包含小数点的数字视为字符串。

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.

您应该使用 bc 来执行此类计算,就像在 dogbane 的解决方案中一样,只是您应该使用引号对表达式进行转义,以便该*字符不会导致不需要的外壳扩展。

echo "$vpct*15" | bc

回答by dogbane

You should use bc for floating point arithmetic:

您应该使用 bc 进行浮点运算:

echo "$vpct*15" | bc

回答by Paused until further notice.

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

如果您有可用的 ksh,它将执行浮点运算。

回答by Paused until further notice.

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

Shebang 应该写成#!And 无论如何$(())只适用于整数。

回答by Cedric

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

$(( $vpct * 15 )) // (添加一个 $ 符号应该这样做)