2

Here's a simple line from a bigger piece of code which is what I am confused about.

if [ $some_line == "text" ]
then

Then I went on to use the same code for another program that I was working on but the code didn't work UNLESS I changed "==" to "=". I've gone through a few threads here that suggests both of them act the same way so it doesn't matter if you use single or double equals.

if [ $some_line = "text" ]
then

So the first piece of code works on server1 but doesn't on server2 UNLESS I change it to "single equals". Both the servers have exactly the same environment.

Can anyone explain? Thanks!

EDIT - I am running the script as "bash myscript.sh" everytime.

Nishant
  • 51
  • Please [edit[ your question and i) tell us how you are launching the script (sh script.sh? bash script.sh? Just script.sh? Something else?) and also show us the output of ls -l /bin/sh on both machines. – terdon May 30 '18 at 11:40
  • 1
    Please explain "does not work". Did it do something unexpected or produce an error, or something else? – Kusalananda May 30 '18 at 11:48
  • And did you check if you have some special characters in the variable? – Romeo Ninov May 30 '18 at 11:49
  • 1
    "So the first piece of code works on server1 but doesn't on server2", but "Both the servers have exactly the same environment.". I'd say the premise of the question is obviously wrong. If the environment between the servers were the same, both = and == would behave the same on both of them. – ilkkachu May 30 '18 at 11:49
  • On the contrary, many answers here such as https://unix.stackexchange.com/a/382012/5132 , https://unix.stackexchange.com/a/16110/5132 , and https://unix.stackexchange.com/a/168288/5132 say that it does matter. – JdeBP May 30 '18 at 12:19

1 Answers1

3

== and = are equivalent inside [ ] tests in bash.

== doesn't work in sh, only =

Are you running both scripts with the same shell?

Example:

$ cat test1
#!/bin/bash
if [ "a" == "a" ];then echo match;fi
$ ./test1
match
$ cat test2
#!/bin/bash
if [ "a" = "a" ];then echo match;fi
$ ./test2
match
$ cat test3
#!/bin/sh
if [ "a" = "a" ];then echo match;fi
$ ./test3
match
$ cat test4
#!/bin/sh
if [ "a" == "a" ];then echo match;fi
$ ./test4
./test4: 2  [: a: unexpected operator
terdon
  • 242,166
  • yeah. The only thing that stands out is that this ubuntu server has not been updated since good amount of time due to development reasons. How can I check if both of them are using the same shell / environment while executing the script? – Nishant May 30 '18 at 11:23
  • run ps -o comm $$ to know which shell you are in

    or echo $0

    – dgfjxcv May 30 '18 at 11:23
  • Since you are using bash, do: echo "$BASH_VERSION" –  May 30 '18 at 11:28