Mathias Verhoeven
Mathias Verhoeven

Reputation: 1067

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?

Upvotes: 79

Views: 172645

Answers (6)

akostadinov
akostadinov

Reputation: 18614

I think dc deserves a honorable mention here. It is useful if you have for example a file with 2 values that you want to operate on.

Basic usage like:

dc
5
2
/
p

You get 2. p commands it to spit out the result so far.

dc
1 k 5 10 / p

You get .5 because k sets precision.

For example if file has 2 values you want to divide, you can do

ratio="$(dc <<< "6 k $(<myfile) / p")"

Upvotes: 0

Puspam
Puspam

Reputation: 2777

You can also use Python for this task.
Type python -c "print( $var1 / float($var2) )"

Upvotes: 2

rouble
rouble

Reputation: 18201

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

Upvotes: 28

Walter Wahlstedt
Walter Wahlstedt

Reputation: 39

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

Upvotes: 2

m47730
m47730

Reputation: 2261

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

Upvotes: 124

Tom Fenech
Tom Fenech

Reputation: 74665

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.

Upvotes: 24

Related Questions