Sudhir Sudhir - 1 year ago 122
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:

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.


Any pointers please?


Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download