我试图在Bash脚本中划分两个图像宽度,但Bash给我0作为结果:

RESULT=$(($IMG_WIDTH/$IMG2_WIDTH))

我确实研究了Bash指南,我知道我应该使用bc,在互联网上的所有例子中,他们都使用bc。在echo中,我试图把同样的东西放在我的SCALE中,但它不起作用。

以下是我在教程中找到的例子:

echo "scale=2; ${userinput}" | bc 

我怎么能让巴斯给我0.5这样的浮点数呢?


当前回答

正如其他人指出的那样,bash没有内置的浮点运算符。

您可以在bash中实现浮点数,甚至不使用bc和awk之类的计算器程序,或者任何与此相关的外部程序。

我在我的项目shellmath中正是这样做的,分三个基本步骤:

把数字分成整数部分和小数部分 使用内置的整数运算符分别处理各个部分,同时注意位值和进位 重新组合结果

作为一个挑逗,我添加了一个演示脚本,使用以x=0为中心的泰勒级数计算e。

如果您有时间,请查看一下。欢迎您的反馈!

其他回答

There are scenarios in wich you cannot use bc becouse it might simply not be present, like in some cut down versions of busybox or embedded systems. In any case limiting outer dependencies is always a good thing to do so you can always add zeroes to the number being divided by (numerator), that is the same as multiplying by a power of 10 (you should choose a power of 10 according to the precision you need), that will make the division output an integer number. Once you have that integer treat it as a string and position the decimal point (moving it from right to left) a number of times equal to the power of ten you multiplied the numerator by. This is a simple way of obtaining float results by using only integer numbers.

稍微改进一下马文的回答:

RESULT=$(awk "BEGIN {printf \"%.2f\",${IMG_WIDTH}/${IMG2_WIDTH}}")

BC并不总是安装包。

它不是真正的浮点数,但如果你想在一次调用bc时设置多个结果…

source /dev/stdin <<<$(bc <<< '
d='$1'*3.1415926535897932384626433832795*2
print "d=",d,"\n"
a='$1'*'$1'*3.1415926535897932384626433832795
print "a=",a,"\n"
')

echo bc radius:$1 area:$a diameter:$d

计算半径为$1的圆的面积和直径

** bash/shell中的注入安全浮点数学

注意:这个回答的重点是为在bash(或其他shell)中执行数学的注入安全解决方案提供思路。当然,同样也可以使用,只需稍作调整即可执行高级字符串处理等。

所提出的大多数解决方案都是使用外部数据(变量、文件、命令行、环境变量)动态构造小脚本。外部输入可用于向引擎中注入恶意代码,其中很多是恶意代码

下面是使用各种语言进行基本数学计算的比较,其中结果为浮点数。它计算A + B * 0.1(作为浮点数)。

所有的解决方案都试图避免创建难以维护的动态脚本,而是使用静态程序,并将参数传递给指定的变量。它们将安全地处理具有特殊字符的参数-减少代码注入的可能性。例外是'BC',它不提供输入/输出功能

例外是'bc',它不提供任何输入/输出,所有数据都来自stdin中的程序,所有输出都到stdout。所有计算都在沙箱中执行,不允许出现副作用(打开文件等)。理论上,注射是安全的设计!

A=5.2
B=4.3

# Awk: Map variable into awk
# Exit 0 (or just exit) for success, non-zero for error.
#
awk -v A="$A" -v B="$B" 'BEGIN { print A + B * 0.1 ; exit 0}'

# Perl
perl -e '($A,$B) = @ARGV ; print $A + $B * 0.1' "$A" "$B"

# Python 2
python -c 'import sys ; a = float(sys.argv[1]) ; b = float(sys.argv[2]) ; print a+b*0.1' "$A" "$B"

# Python 3
python3 -c 'import sys ; a = float(sys.argv[1]) ; b = float(sys.argv[2]) ; print(a+b*0.1)' "$A" "$B"

# BC
bc <<< "scale=1 ; $A + $B * 0.1"

现在是尝试zsh的最佳时机,它是一个(几乎)bash超集,具有许多其他不错的特性,包括浮点数学。下面是你的例子在zsh中的样子:

% IMG_WIDTH=1080
% IMG2_WIDTH=640
% result=$((IMG_WIDTH*1.0/IMG2_WIDTH))
% echo $result
1.6875

这篇文章可能会帮助你:bash -值得切换到zsh随意使用?