3

I wrote the code below:

for j in `cat output_10.txt`

do

dri=`echo $j |cut -d':' -f1` 
nu=`echo $j |cut -d':' -f2`
tot=`echo $j |cut -d':' -f3`
fre=`echo $j |cut -d':' -f4`


if [ $fre > 2 ]
                then
                echo "<td align="Center" bgcolor="#81F781"> $fre </td>" >>mailbody.html
                else
                echo "<td align="Center" bgcolor="#B40404"> $fre </td>" >>mailbody.html
fi
done 

where the value of fre is being read from output_10.txt file and is a something like 9.8. The issue is that the else condition is not working even if the value of the $fre is less than 2 . I want if the value of $fre is less than 2, the else condition work and it should display the color red in my HTML page.

As of now green color is displayed in my HTML page for both the cases.

2 Answers2

3

Bash cannot do floating point comparisons. You need to call out to another tool, here I show bc reading input from a bash here-string.

Use the read command to extract the fields from the lines of your file instead of calling cut several times.

You cannot embed double quotes inside a double quoted string without escaping them. Use printf to make the quoting a little easier.

#!/bin/bash
while IFS=: read dri nu tot fre rest_of_line; do
    if [[ $(bc <<< "$fre > 2") == "1" ]]; then
        color=81F781
    else
        color=B40404
    fi
    printf '<td align="Center" bgcolor="#%s">%s</td>' $color $fre >>mailbody.html
done <  output_10.txt
glenn jackman
  • 85,964
0
[ $fre > 2 ]

This is [ $fre ] with the (empty) output redirected to the file 2. Remember that the character > introduces an output redirection.

Use the -gt operator to perform a numeric comparison: [ "$fre" -gt 2 ]. (Incidentally, always use double quotes around variable substitutions unless you understand why you must leave them out.) Bash also has a [[ … ]] syntax where > is parsed as a comparison operator and not as a redirection, but that operator performs a lexicographic comparison, i.e. it compares strings, so 9 > 10.

Bash doesn't support floating point. You can call an external program such as bc. Alternatively, you can use an ad hoc way of comparing a decimal number with an integer:

fre_int=${fre%.*} # truncate the part after the decimal point
if [ "$fre_int" -ge 2 ] && [ "$fre" != 2 ]; then …