single 和 double 等於兩者的行為不同

single 和 double 等於兩者的行為不同

這是一段更大的程式碼中的一行簡單的程式碼,這正是我感到困惑的地方。

if [ $some_line == "text" ]
then

然後我繼續對我正在開發的另一個程式使用相同的程式碼,但程式碼不起作用,除非我將“==”更改為“=”。我在這裡瀏覽了一些線程,表明它們的行為方式相同,因此使用單等號或雙等號並不重要。

if [ $some_line = "text" ]
then

因此,第一段程式碼可以在 server1 上運行,但不能在 server2 上運行,除非我將其更改為「單一等於」。兩台伺服器的環境完全相同。

誰能解釋一下嗎?謝謝!

編輯 - 我每次都將腳本運行為“bash myscript.sh”。

答案1

==且在 中的測試=中是等效的。[ ]bash

==不起作用sh,僅=

您是否使用相同的 shell 來執行這兩個腳本?

例子:

$ 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

相關內容