Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide two variables in bash

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?

like image 797
Mathias Verhoeven Avatar asked May 22 '15 13:05

Mathias Verhoeven


2 Answers

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

like image 138
m47730 Avatar answered Oct 01 '22 03:10

m47730


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 
like image 35
rouble Avatar answered Oct 01 '22 03:10

rouble