Why is both the if and else executed? [closed]

2019-08-15 01:17发布

问题:

My code is:

if [ "$server" == "a" ]; then
        echo "apache"
fi

if [ "$server" ==  "t"   ]
then
        echo "tomcat"
else
        echo "Entered"
fi

The value of the $server is t. I expect the value tomcat to be printed on the console. But Entered is printed too!

I'm confused about this. How come both the if and else statements are executed?

回答1:

The else branch should only ever execute if the preceding if statement evaluates to false. There's not really any exceptions to that rule that I'm aware of. There's probably something else fishy going on in the bash file that's causing the issue.

Make sure bash is what is executing the script. #!/bin/bash should be on the first line.



回答2:

To solve your problem, do something like this:

  • Put echo statements into every branch:

    if [ "$server" == "a" ]; then
        echo "in branch apache"
        echo "apache"
    fi
    
    if [ "$server" ==  "t"   ]
    then
            echo "in branch tomact"
            echo "tomcat"
    else
            echo "in else branch"
            echo "Entered"
    fi
    

If you still can't spot the problem, one of these:

  • Execute the script by using the -x flag

    bash -x <scriptname>
    
  • Comment out every line... then comment in line by line and see what result you get