0

I'm trying to write what would seem to be a simple if statement in most languages, however in bash this doesnt seem to work at all.

When I run the script it always enters the first if statement. Can anyone offer help me as to what I am doing wrong?

PERC=.5
    if [  "$PERC" > "1.00" ]
            then
                    echo "Entered first statement"
            else
                    if [ "$PERC" < "1.00" ]
                            then
                                    echo "Entered second statement"
                    fi
    fi

Thanks for your help.

  • 1
    Where did you read that `>` and `<` are valid arguments to `[`? – Ignacio Vazquez-Abrams Sep 11 '15 at 10:40
  • @IgnacioVazquez-Abrams I didn't, It's used in java, c++,c,Haskell, and most other languages i have used. I have saw people use it and not use it in bash, I have also saw people use -lt and -gt but that also never worked for me. – Ethan McTiernan Sep 11 '15 at 10:44
  • @IgnacioVazquez-Abrams: `help test` mentions `<` and `>` as string operators, so why shouldn't they be valid arguments, even if unsuitable for comparing numbers (and with redirection in mind)? – Michael Jaros Sep 11 '15 at 11:48

2 Answers2

2

> and < compare strings, not numbers (and must be backslashed or quoted in single [...]). Use -gt, -lt etc. to compare numbers, or use arithmetic conditions:

if (( a < b || b <= c )) ; then

Note, however, that bash only handles integer arithmetics. To compare floats, you can use bc:

if [[ 1 == $( bc <<< '1.5 < 1.00' ) ]] ; then
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Thanks for your reply. I just copied your bottom example exactly and i get an error saying : syntax error near `)' line 7: `if [[ 1== $( bc <<< '1.5 < 1.00' ) ]]' any ideas? – Ethan McTiernan Sep 11 '15 at 11:28
  • @EthanMcTiernan: A space is missing before `==` in your exact copy. – choroba Sep 11 '15 at 11:35
2

> and < are the I/O redirection operators. So

if [ "$PERC" > "1.0" ]

is executing the command [ "$PERC ], redirecting the output to the file 1.0, and then if is testing whether the command succeeded. [ "$PERC" ] simply tests whether "$PERC" is a non-empty string.

To use them as operators in the test command, you need to quote or escape them:

if [ "$PERC" '>' "1.0" ]

You could also use bash's [[ conditional syntax instead of the [ command:

if [[ $PERC > "1.0" ]]
Barmar
  • 741,623
  • 53
  • 500
  • 612