itsh
itsh

Reputation: 1123

Unexpected output in bash shell script

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

Upvotes: 2

Views: 146

Answers (1)

chepner
chepner

Reputation: 532398

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.

Upvotes: 6

Related Questions