Linux shell编程字符串比较语法

jeo*_*eon 17 linux string shell compare

是什么区别===比较在Linux的shell编程字符串?

也许以下代码有效:

if [ "$NAME" = "user" ]
then
    echo "your name is user"
fi
Run Code Online (Sandbox Code Playgroud)

但我认为这不是一个正确的语法.它将用于比较逐字符串==.

什么是正确的?

Joh*_*tta 23

单一的等于是正确的

string1 == string2

string1 = string2

如果字符串相等则为True.'='应与POSIX一致性的测试命令一起使用

NAME="rafael"
USER="rafael"
if [ "$NAME" = "$USER" ]; then
    echo "Hello"
fi
Run Code Online (Sandbox Code Playgroud)


Fin*_*ner 11

通常,=运算符在比较字符串时与==的作用相同.

注意:==比较运算符在双括号测试中的行为与单括号内的行为不同.

[[ $a == z* ]]   # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

[ $a == z* ]     # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
Run Code Online (Sandbox Code Playgroud)

来源:http://tldp.org/LDP/abs/html/comparison-ops.html


Dar*_*uuk 4

这些页面解释了 bash 中的各种比较运算符:

在第二个链接页面上,您会发现:

==

    is equal to

    if [ "$a" == "$b" ]

    This is a synonym for =.
Run Code Online (Sandbox Code Playgroud)

  • 这个答案本身现在是谷歌上的第一批点击率之一。这就是为什么只回答“Google it”。并不总是一个好的政策。如果您没有注意到,StackOverflow 的页面排名非常高。 (11认同)
  • SO 的想法是提供比“10 秒谷歌搜索答案”更好的东西吗? (3认同)
  • [这之前已经出现过](http://meta.stackexchange.com/questions/15650/ban-lmgtfy-let-me-google-that-for-you-links)此评论是在您对您的回答 (2认同)