Fractions in bash/shell terminal


Math using bash variables is not straight forward and I always end up forgetting the rules, so I am outlining them here with examples.


I needed to calculate how much of an overlap there was between my bed file of approximated enhancers in the mouse genome in a specific cell type and the mm10 enhancer list from Fantom5.

So first I used bedtools2 to get the intersection and wc -l to get the raw numbers.

# get intersection
bedtools intersect -a F5.mm10.enhancers.bed -b P7_enhancers.bed > overlap.bed
# save wc -l output to variable for the overlap
# this will be my numerator
OVERLAP=($(wc -l P7_overlap.bed ))
# save wc -l output to variable for the enhancer set 
# this is be my denominator
TOTAL=($(wc -l F5.mm10.enhancers.bed ))
echo $TOTAL

Then simply divide the number of lines from the intersection and number of lines in the enhancer list.

echo $$(OVERLAP / TOTAL))

But the since this division will result in a number less than 0 bc must be used

echo "scale=2 ; $OVERLAP / $TOTAL" | bc

To save this output to a variable

OUTPUT=($( echo "scale=2 ; $OVERLAP / $TOTAL" | bc ))
echo $OUTPUT

Note : there are other was to compute this in a way that return a float.