Rock Rock - 2 months ago 10
Bash Question

Syntax error: invalid arithmetic operator in bash scripting

In my bash script I am trying floating point comparison e.g.

a=0.32
b=0.38


I have written below snippet,

if [[ $(`bc-l <<< "$b > $a"`) -eq 0 ]]; then
echo "true"
else
echo "false"
fi


Please advice.

Answer

Make sure that you are actually running in bash shell.

#!/bin/bash
a=0.32; b=0.18; c=0.60    
if [[ $(bc -l <<< "$a > $b") -eq 1 ]]; then
    echo "$a > $b"
else
    echo "$a <= $b"
fi

if [[ $(bc -l <<< "$a > $c") -eq 1 ]]; then
    echo "$a > $c"
else
    echo "$a <= $c"
fi

Or equivalently:

#!/bin/bash
a=0.32; b=0.18; c=0.60    

if [[ "$a" > "$b" ]]; then
    echo "$a > $b"
else
    echo "$a <= $b"
fi

if [[ "$a" > "$c" ]]; then
    echo "$a > $c"
else
    echo "$a <= $c"
fi