Reputation: 25
According to the problem stated in the below link:
My code is working fine in Mac OSX terminal, but while submitting the same code in Hackerrank one of the test case is failing. I am not sure why this is happening. Would really appreciate any answers.
read X
read Y
if [[ $X > $Y ]]
then
echo "X is greater than Y"
elif [[ $X < $Y ]]
then
echo "X is less than Y"
else
echo "X is equal to Y"
fi
HackerRank Custom Test Case:
Compilation Successful
Input (stdin)
-100
100
Your Output
X is greater than Y
Upvotes: 1
Views: 936
Reputation: 104024
You can use the Bash double-parenthesis context ((...))
vs test context [[ ... ]]
to get more typical arithmetic comparisons:
x=-5
y=5
if ((x>y)); then
echo "X is greater than Y"
elif ((x<y)); then
echo "X is less than Y"
else
echo "X is equal to Y"
fi
Or use an integer comparison inside [[ ... ]]
test:
if [[ "$x" -gt "$y" ]]; then
echo "X is greater than Y"
elif [[ "$x" -lt "$y" ]]; then
echo "X is less than Y"
else
echo "X is equal to Y"
fi
Inside [[ ... ]]
the <
,>
or ==
tests string comparisons.
Both of these methods only work with integers; to use floats, you need to use awk
, bc
or other float interpreter. Be sure to use double quotes "$x"
in the [[ test ]]
and the quotes and sigil are not required for (( ))
With user input, be sure to test that $x
and $y
are actual
numbers. Good tests here...
Upvotes: 4
Reputation: 125918
I'm not sure why you're getting that result; I get "X is less than Y" in actual bash. However, your script is actually wrong in a different way: in [[ ]]
, <
and >
do alphabetic comparison rather than numeric comparison. To understand the difference, consider that [[ 5 < 1000 ]]
will come out as false, because "5" comes after "1" in character sorting order. To do numeric comparison, use -lt
and -gt
instead.
Upvotes: 3