bash 在bash中划分两个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30398014/
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
Divide two variables in bash
提问by Mathias Verhoeven
I am trying to divide two var in bash, this is what I've got:
我试图在 bash 中划分两个 var,这就是我所得到的:
var1=3;
var2=4;
echo ($var1/$var2)
I always get a syntax error. Does anyone knows what's wrong?
我总是收到语法错误。有谁知道出了什么问题?
回答by m47730
shell parsing is useful only for integer division:
shell 解析仅对整数除法有用:
var1=8
var2=4
echo $((var1 / var2))
output: 2
输出:2
instead your example:
而不是你的例子:
var1=3
var2=4
echo $((var1 / var2))
ouput: 0
输出:0
it's better to use bc:
最好使用 bc:
echo "scale=2 ; $var1 / $var2" | bc
output: .75
输出:.75
scaleis the precision required
scale是所需的精度
回答by Tom Fenech
There are two possible answers here.
这里有两个可能的答案。
To perform integer division, you can use the shell:
要执行整数除法,您可以使用 shell:
$ echo $(( var1 / var2 ))
0
The $(( ... ))
syntax is known as an arithmetic expansion.
该$(( ... ))
语法称为算术扩展。
For floating point division, you need to use another tool, such as bc
:
对于浮点除法,您需要使用另一个工具,例如bc
:
$ bc <<<"scale=2; $var1 / $var2"
.75
The scale=2
statement sets the precision of the output to 2 decimal places.
该scale=2
语句将输出的精度设置为 2 个小数位。
回答by rouble
If you want to do it without bc, you could use awk:
如果你想在没有 bc 的情况下做到这一点,你可以使用 awk:
$ awk -v var1=3 -v var2=4 'BEGIN { print ( var1 / var2 ) }'
0.75
回答by Walter Wahlstedt
#!/bin/bash
var1=10
var2=5
echo $((var1/var2))