0

When trying to compare 2 numbers which are decimal in an if condition, I am getting the following error

./cpu.sh: line 8: ((: 1 -gt 1.0 | bc : syntax error in expression (error token is "1.0 | bc ")

./cpu.sh: line 8: ((: 0 -gt 1.0 | bc : syntax error in expression (error token is "1.0 | bc ")

./cpu.sh: line 8: ((: 2 -gt 1.0 | bc : syntax error in expression (error token is "1.0 | bc ")

./cpu.sh: line 8: ((: 3.0 -gt 1.0 | bc : syntax error: invalid arithmetic operator (error token is ".0 -gt 1.0 | bc ")

#!/bin/bash
val1=$*
for i in $val1
do
    if (( $i -gt 1.0 | bc ))
    then
        echo $i
    fi
done
Andy Preston
  • 779
  • 4
  • 9
  • 23
spark
  • 1
  • What arguments do you use when calling this script? – Andy Preston Mar 03 '23 at 09:31
  • 1
    The correct way to do what I think you're trying to achieve can be found here: [How Can I Compare Two Floating Point Numbers in bash](https://stackoverflow.com/questions/8654051/how-can-i-compare-two-floating-point-numbers-in-bash) – Andy Preston Mar 03 '23 at 09:37

2 Answers2

4

(( ... )) expects an arithmetic expression. It doesn't handle -gt and | means bitwise or, not a pipe.

Arithmetic expressions can't handle decimals in bash. Using bc is one of the solutions, but you can't combine it with (( ... )) in this way. You need the output of bc, so use command substitution. bc doesn't understand -gt, it uses the traditional < and > to compare numbers.

if (( $(bc <<< "$i > 1.0") )) ; then
    echo $i
fi
choroba
  • 231,213
  • 25
  • 204
  • 289
0

Note that when you use a greater than sign (-gt) in an if statement to compare numeric sizes, both operands should be numeric, otherwise the comparison may not be as expected. In this example, when the value of i is 1.1, you should be able to output this value, but in fact this code cannot output anything because using a greater than sign to compare strings is not a numerical comparison, and you should use commands such as double brackets or bc to perform numerical calculations.

#!/bin/bash
for i in "$@"
do
    if (( $(echo "$i > 1.0" | bc -l) ))
    then
        echo $i
    fi
done

It is also important to note that using "$@" in the for loop to iterate through all parameters ensures that each parameter is handled correctly, even if it contains special characters such as spaces.

Thysrael
  • 41
  • 6