Reputation: 1
Below is my script, I am not getting the right output, I am typing alice I am getting bob as output, but when i am typing bob I should get alice as output, but i am getting bob as output. Kindly let me know what's the error in my script
#!/bin/bash
echo "Enter your name"
read a
if [ $a==alice ];
then
echo "bob"
elif [ $a==bob ];
then
echo "alice"
else
echo "STDERR"
fi
Upvotes: 0
Views: 50
Reputation: 14955
Wrong syntax, should be:
[[ $a == alice ]]
Check: http://tldp.org/LDP/abs/html/comparison-ops.html
Upvotes: 2
Reputation: 84561
Spaces are required surrounding your ==
expression. When using the [
test operator or using the keyword test
, you will want to use the =
for posix compliance and portability:
[ "$a" = alice ] # remember to quote your variable when comparing strings
While ==
is permissive with [
or test
, you will lose portability. Alternatively, if you are using [[
operator, then ==
is correct:
[[ "$a" == alice ]] # quoting is not required, but is good practice.
Upvotes: 0
Reputation: 881463
You should put spaces around your ==
operator, so that it's a three-argument form of [
.
Without the spaces, it's using the one-argument form which gives true if the string length is non-zero (as it is with the string bob==alice
).
Upvotes: 1