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?
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.
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: