Linux shell编程字符串比较语法

18

在Linux Shell编程中,===用于比较字符串的区别是什么?

也许以下代码可以工作:

if [ "$NAME" = "user" ]
then
    echo "your name is user"
fi

但我认为这不是正确的语法。应该使用==语句来比较字符串。

那么正确的是什么?

4个回答

23

单个等号是正确的

string1 == string2

string1 = string2

如果字符串相等,则为True。'='应与测试命令一起使用以符合POSIX标准。

NAME="rafael"
USER="rafael"
if [ "$NAME" = "$USER" ]; then
    echo "Hello"
fi

1
参考:http://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html#Bash-Conditional-Expressions - user2697615

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).

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


谢谢!我一直在为一个问题苦苦挣扎,原来是我使用了单方括号而不是双方括号。 - cbowns

4

2
这个问题之前已经出现过了:http://meta.stackexchange.com/questions/15650/ban-lmgtfy-let-me-google-that-for-you-links这条评论是在你对答案进行多次修改之前发表的。 - Diarmaid
3
SO 的理念是提供比“在谷歌上搜索 10 秒钟找到答案”更好的东西吗? - FruitBreak
11
这篇答案现在已成为谷歌搜索结果中的前几名之一。这就是为什么仅回答“Google一下”并不总是一个好的策略。如果您没有注意到,StackOverflow的页面排名非常高。 - KatDevsGames
粗鲁的回答,考虑到第一个结果指向SO,你是在尝试引入一个搜索谷歌的无限循环吗? - Frederic Yesid Peña Sánchez
1
值得注意的是,如果这是一个#!/bin/sh程序,而不是#!/bin/bash程序,在我的16.10 Ubuntu服务器上我不能使用双等号。我猜这就是John Giotta在下面的答案中提到的关于POSIX一致性的提示。 - Zut
显示剩余2条评论

1

你可以在这里或者这里看一下。个人而言,我使用case来比较字符串。

case "$string1" in
  "$string2" ) echo "matched";;
  *) echo "not matched";;
esac

我不需要知道应该使用哪个运算符


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接