-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
1
  • 3
    From man bash: "When used with [[, the < and > operators sort lexicographically using the current locale." Commented Sep 9, 2020 at 1:06

3 Answers 3

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
2
  • 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 Commented Sep 9, 2020 at 14:03
  • 1
    No worries. There are no silly questions, providing you follow a few sensible guidelines. Commented Sep 9, 2020 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

2

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

3
  • 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 ") Commented Sep 9, 2020 at 1:21
  • 1
    @Jacksonkr Bash does not do floats. A good starting point for questions like these is to consult man bash. Commented Sep 9, 2020 at 1:21
  • @John1024 What about like this Commented Sep 9, 2020 at 1:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.