Search code examples
bashbc

bash unable to compare multiple number conditions with bc


Have tried several different syntax methods to make bash test between number ranges for floating point numbers and cannot get this to work. Whole numbers work, so do statements without the && operator. I must be missing something obvious.

Essentially 70 and below is "ok", between 70.1 and 79.9 is "warn", 80 and above is "critical"

Thanks in advance for any help or advice.

#! /bin/bash

number=70.1
echo $number

if (( $(echo "$number < 70" | bc -l) )); then echo "OK";fi
if (( $(echo "$number >= 70" && "$number < 80" | bc -l) )); then echo "WARN";fi
if (( $(echo "$number >= 80" | bc -l) )); then echo "CRITICAL";fi

Solution

  • echo "$number >= 70" && "$number < 80" are two commands in bash. The first is echo and the second command is "70.1 < 80" (pretty sure there is no such command on your system).

    You probably wanted to write echo "$number >= 70 && $number < 80" which is just one command.

    By the way: In bash you can use bc <<< ... instead of echo ... | bc.

    if (( $(bc <<< "$number < 70") )); then echo "OK"; fi
    if (( $(bc <<< "$number >= 70 && $number < 80") )); then echo "WARN"; fi
    if (( $(bc <<< "$number >= 80") )); then echo "CRITICAL"; fi
    

    or with restructured control flow

    if (( $(bc <<< "$number < 70") )); then
      echo "OK";
    elif (( $(bc <<< "$number < 80") )); then
      echo "WARN"
    else
      echo "CRITICAL"
    fi