0

I have 2 variables which i get as input from bash, i want to print the relation between the 2 variables i.e if X is greater or less or equal to y , here is how i am trying to achieve

read X
read Y

if ["$X" < "$Y"]
    then 
        echo "X is less than Y"
else 
    if ["$X" > "$Y"]
    then 
        echo "X is Greater than y"
    else 
        echo "X is equal to Y"
    fi
fi

I am getting the error

line 4: 2]: No such file or directory
line 8: [5: command not found
Teja Reddy
  • 561
  • 1
  • 4
  • 12
  • 2
    You need [spaces around the `[` and `]`](https://stackoverflow.com/questions/9581064). Also, in a `[ ]` test, you need to escape or quote `<` and `>`, or they'll be treated as I/O redirects rather than operators (or you could use `[[ ]]` instead of `[ ]`, as it doesn't have this problem) -- but if you want [numeric comparison instead of alphabetical](https://stackoverflow.com/questions/42745497), you need to use `-lt` and `-gt` instead of `<` and `>`. Finally: use [shellcheck.net](https://www.shellcheck.net). – Gordon Davisson Jun 15 '23 at 07:35

1 Answers1

1

Edit

This looks to be a duplicate of How can I compare numbers in Bash?. Here are some of the answers to that question applied to your example:


Try this (POSIX):

#!/bin/sh

read X
read Y

if [ "$X" -lt "$Y" ]
    then
        echo "X is less than Y"
else
    if [ "$X" -gt "$Y" ]
    then
        echo "X is Greater than y"
    else
        echo "X is equal to Y"
    fi
fi

Or this (POSIX):

#!/bin/sh

read X
read Y

if [ "$X" \< "$Y" ]
    then
        echo "X is less than Y"
else
    if [ "$X" \> "$Y" ]
    then
        echo "X is Greater than y"
    else
        echo "X is equal to Y"
    fi
fi

Or this (bash):

#!/bin/bash

read X
read Y

if [[ "$X" < "$Y" ]]
    then
        echo "X is less than Y"
else
    if [[ "$X" > "$Y" ]]
    then
        echo "X is Greater than y"
    else
        echo "X is equal to Y"
    fi
fi
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46