Reason Sarker Reason Sarker - 5 months ago 21
Bash Question

Logical error in bash script

I have been writing a bash script that calculates a False Rejection Rate between the values of two files. Both of the files file1.txt and file2.txt contain binary values. All the errors have been fixed, yet the output is 0. I wonder if I have made any mistake in my script unknowingly as I am very new in writing shell scripts and haven't mastered them yet.

#!/bin/bash
nfr=0
ns=0
frr=0

while read file1 <&3 && read file2 <&4; do
if [$file1 == "1" ]
then
let "ns++"
fi

if [ "$file1" == "1" ] && [ "$file2" != "1" ]
then
let "nfr++"
else
continue
fi
done 3< ./file1.txt 4< ./file2.txt

let frr="((nfr / ns) * 100)"
echo $frr


file1.txt:

2
2
2
2
1
1
1
1
1
2
1
1
2
2


file2.txt:

2
2
2
2
2
2
1
1
1
2
1
1
2
2

Answer

The main problem is that the shell uses integer arithmetic, so your division will always be truncated to zero.

Your script has a syntax error (no space after a [), and it does not double quote the variable references in the [] expression which will lead to syntax errors if there is an empty line in the input file.

You can use dc for arbitrary precision arithmetic if installed.

Here is my version:

#!/bin/bash
declare -i nfr=0
declare -i ns=0

while read file1 <&3 && read file2 <&4; do
    if [ "$file1" == "1" ]
    then
        let "ns++"

        if [ "$file2" != "1" ]
        then
            let "nfr++"
        fi
    fi
done 3< ./file1.txt 4< ./file2.txt

# this will remove the decimal fraction
echo $((nfr * 100 / ns))
# this will print the value with a precision of 5
precision=5
echo "$precision k$nfr $ns/100*p" | dc