问题描述
我的服务器上有一个备份脚本,该脚本执行备份作业,并向我发送一份备份文件的摘要,包括新备份文件的大小.作为脚本的一部分,我想将文件的最终大小除以(1024 ^ 3),以从文件大小(以字节为单位)获得以GB为单位的文件大小.
I have a backup script on my server which does cron jobs of backups, and sends me a summary of files backed up, including the size of the new backup file. As part of the script, I'd like to divide the final size of the file by (1024^3) to get the file size in GB, from the file size in bytes.
由于bash没有浮点计算,因此我尝试使用管道对bc进行计算以获得结果,但是我对基本示例感到困惑.
Since bash does not have floating point calculation, I am trying to use pipes to bc to get the result, however I'm getting stumped on basic examples.
但是,我试图将Pi的值调整为一个比例,
I tried to get the value of Pi to a scale, however,
即使以下方法可行:
~ #bc -l
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
4/3
1.33333333333333333333
22/7
3.14285714285714285714
q
0
quit
非交互式版本不起作用:
A non interactive version does not work:
#echo $(( 22/7 )) | bc
3
这有效:
#echo '22/7' | bc -l
3.14285714285714285714
但是我需要使用变量.因此,以下操作无效无济于事:
But I need to use variables. So it doesnt help that the following does not work:
#a=22 ; b=7
#echo $(( a/b )) | bc -l
3
我显然在Bash中使用变量的语法中缺少某些内容,并且可能与一些指针"一起使用来误解我的内容.
I'm obviously missing something in the syntax for using variables in Bash, and could use with some 'pointers' on what I've misunderstood.
正如DigitalRoss所说,我可以使用以下内容:
As DigitalRoss said, I can use the following:
#echo $a / $b | bc -l
3.14285714285714285714
但是我不能使用复杂的表达式,例如:
However I cant use complex expressions like:
#echo $a / (( $b-34 )) | bc -l
-bash: syntax error near unexpected token `('
#echo $a / (( b-34 )) | bc -l
-bash: syntax error near unexpected token `('
#echo $a / (( b-34 )) | bc -l
-bash: syntax error near unexpected token `('
有人可以给我一种正确的语法,以便通过复杂的算术表达式获得浮点结果吗?
Can someone give me a working correct syntax for getting floating point results with complicated arithmetic expresssions?
推荐答案
只需对表达式进行双引号("
)
Just double-quote ("
) the expression:
echo "$a / ( $b - 34 )" | bc -l
然后bash将扩展$
变量并忽略其他所有内容,并且bc
将看到带括号的表达式:
Then bash will expand the $
variables and ignore everything else and bc
will see an expression with parentheses:
$ a=22
$ b=7
$ echo "$a / ( $b - 34 )"
22 / ( 7 - 34 )
$ echo "$a / ( $b - 34 )" | bc -l
-.81481481481481481481
这篇关于浮点导致Bash整数除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!