Divide two variables in bash

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-28 06:19:11

问题


I am trying to divide two var in bash, this is what I've got:

var1=3;
var2=4;

echo ($var1/$var2)

I always get a syntax error. Does anyone knows what's wrong?


回答1:


shell parsing is useful only for integer division:

var1=8
var2=4
echo $((var1 / var2))

output: 2

instead your example:

var1=3
var2=4
echo $((var1 / var2))

ouput: 0

it's better to use bc:

echo "scale=2 ; $var1 / $var2" | bc

output: .75

scale is the precision required




回答2:


There are two possible answers here.

To perform integer division, you can use the 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 <<<"scale=2; $var1 / $var2"
.75

The scale=2 statement sets the precision of the output to 2 decimal places.




回答3:


If you want to do it without bc, you could use awk:

$ awk -v var1=3 -v var2=4 'BEGIN { print  ( var1 / var2 ) }'
0.75



回答4:


#!/bin/bash
var1=10
var2=5
echo $((var1/var2))


来源:https://stackoverflow.com/questions/30398014/divide-two-variables-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!