0

I am sure I must be doing something wrong, but I can't figure out what. A simple string comparison does not seem to be working. My shell script is as follows:

echo $HOME
echo $1
if [ $# -eq 0 ];
then
 echo "No Params!"
elif [ "$1"="prod" ];
then
 echo "Production"
else
 echo "Incorrect Params"    
fi

When I run the script without any params, I get the correct output. i.e. "No Params"

However, when I pass a parameter other than prod, the script still outputs "Production" whereas I expect it to echo "Incorrect Params"

I looked at various places for string comparison within a shell script, e.g. Compare a string in Unix and they seemed to have followed the same approach.

Where am I going wrong?

Community
  • 1
  • 1
shashi
  • 4,616
  • 9
  • 50
  • 77
  • 2
    http://shellcheck.net is your friend here. `TL;DR`: change `[ "$1"="prod" ]` to `[ "$1" = "prod" ]` – anishsane Jul 14 '16 at 16:03
  • Thanks, could you please post that as an answer so that I can mark it as such? – shashi Jul 14 '16 at 16:05
  • You need spaces around `=` operator. `[ "a"="b" ]` is equivalent to `[ "a=b" ]` i.e. `[ -n "a=b" ]`. Since `"a=b"` is a non-empty string, this condition is always true. Also, `[` is not a `bash` keyword. `[` is `/usr/bin/[`; but it is usually overridden by bash built-in `[` for performance reasons. So, for command interpretation perspective, in `[ "a"="b" ]` statement, `[` has 2 arguments : `a=b` & `]` which is the condition terminator. in case of `[ "a" = "b" ]`, it has 4 arguments: `a`, `=` and `b`. It interprets them as separate tokens & process them as you were expecting. – anishsane Jul 14 '16 at 16:15

0 Answers0