2

For the below script I am expecting the output to be msg_y and msg_z. But it is printing msg_x and msg_z. Can somebody explain to me what is going on?

#!/bin/bash
 set -x

vr=2
echo $vr
if [ $vr > 5 ]
then
        echo "entered 1st if"
        echo "msg_x"

        echo "out of 1st if"

        if [ $vr < 8 ]; then
        echo "in of 2nd if"
        echo "msg_y"

        else
        echo "msg_z"
        fi

else
        if [ $vr > 1 ]; then echo "msg_y"

        else echo "msg_z"
        fi
fi

1 Answer 1

6

This expression

[ $vr > 5 ]

is being parsed as an output redirection; check to see if you have a file named "5" now. The output redirection is vacuously true. Note that the usual admonition to quote parameters inside a test expression would not help here (but it's still a good idea).

You can escape the > so that it is seen as an operator in the test command:

if [ "$vr" \> 5 ]; then

or you can use the integer comparison operator -gt

if [ "$vr" -gt 5 ]; then.

Since you are using bash, you can use the more robust conditional expression

if [[ $vr > 5 ]]; then

or

if [[ $vr -gt 5 ]]; then

or use an arithmetic expression

if (( vr > 5 )); then

to do your comparisions (likewise for the others).


Note: although I showed how to make > work as a comparison operator even when surrounded by integers, don't do this. Most of the time, you won't get the results you want, since the arguments are compared lexicographically, not numerically. Try [ 2 \> 10 ] && echo What? Either use the correct integer comparison operators (-gt et al.) or use an arithmetic expression.

Sign up to request clarification or add additional context in comments.

2 Comments

That's a very clear explanation. Appreciate it. And yes a file called "5" got created.
It is not correct to say "The output redirection is vacuously true". The string $vr is non-empty, and that is why [ $vr > 5 ] is true. If vr were unset or an empty string, it would be false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.