Sudhir Sudhir - 5 months ago 25
Bash Question

division in shell script

I am trying to do a simple division of variables in a shell script, but it is somehow not working. May be there I am overlooking something really basic. Below is a script for calculating total number of reads from a bam file for bams files read from a list file. I need to assign the output to a variable and calculate a ratio. This is what I have:

normNum=100000
while IFS=$'\t' read -r bamfile name; do
#for i in $(ls *.bam)
echo $bamfile
mappedReads="$(samtools idxstats $bamfile | awk '{s+=$3} END {print s}')"
echo $normNum
echo $mappedReads
#scalingFactor="$((normNum / mappedReads))"
#echo $scalingFactor
scalingFactor=`printf "%0.3f\n" $((normNum / mappedReads))`
echo $scalingFactor
done < "${file}_temp"


The different prints are giving my correct number except for scalingFactor, which gives me 0.

merged_DupRem.bam
100000
24226512
0.000


Any pointers please?

Thanks..

Answer

Bash does integer math, not floating point. You will need to use awk or bc to provide floating point output. e.g. with bc

scalingFactor=$(printf "scale=3; %d/%d\n" $normNum $mappedReads | bc)