-3
if [[ 6 > 50 ]]; then
    echo "true"
fi

$ bash script.sh

I'm missing something very obvious here. Why is 6 greater than 50 ??

** EDIT **

I'm also try to solve for

if [[ 6.5 > 50 ]]; then
    echo "true"
fi
Jacksonkr
  • 201
  • 2
  • 10
  • 3
    From `man bash`: *"When used with [[, the < and > operators sort lexicographically using the current locale."* – steeldriver Sep 09 '20 at 01:06

3 Answers3

3

If you need to compare floats, the easiest way is to call out to an external tool like awk or bc

a=6.1
b=50
if [[ "$(echo "$a > $b" | bc)" -eq 1 ]]; then echo "a greater than b"; fi
glenn jackman
  • 84,176
  • 15
  • 116
  • 168
  • I'm not as familiar with bash scripting (obviously) so I appreciate you answering my "silly" question with a formative and informational answer rather than exercising contempt on me for knowing less than you in this given situation. Cheers @glennJackman – Jacksonkr Sep 09 '20 at 14:03
  • 1
    No worries. There are no silly questions, providing you [follow a few sensible guidelines](https://unix.stackexchange.com/help/how-to-ask). – glenn jackman Sep 09 '20 at 15:42
3

If you're comparing integers then use

if [[ 6 -gt 50 ]]; then echo "true"; fi

otherwise since bash cannot handle floating point

if (( $(echo "6.5 > 50" | bc -l) )); then echo "true"; fi

boots
  • 61
  • 3
2

You supplied [[ args ]] which is a conditional expression, when you meant to perform arithmetic evaluation which uses the (( condition )) syntax.

chahu418
  • 131
  • 4
  • In certain situations I have a float in there and when I've tried this I get `syntax error: invalid arithmetic operator (error token is ".00 > 50 ")` – Jacksonkr Sep 09 '20 at 01:21
  • 1
    @Jacksonkr Bash does not do floats. A good starting point for questions like these is to consult `man bash`. – John1024 Sep 09 '20 at 01:21
  • @John1024 What about [like this](https://stackoverflow.com/a/23533477/332578) – Jacksonkr Sep 09 '20 at 01:36