Linux shell 编程字符串比较语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5745303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux shell programming string compare syntax
提问by jeon
What is the difference between =
and ==
to compare strings in Linux shell programming?
Linux shell 编程中的字符串=
和==
比较字符串有什么区别?
Maybe the following code works:
也许以下代码有效:
if [ "$NAME" = "user" ]
then
echo "your name is user"
fi
But I think it's not a correct syntax. It would be used to compare string by ==
statement.
但我认为这不是正确的语法。它将用于按==
语句比较字符串。
What is correct?
什么是正确的?
采纳答案by Darhuuk
These pages explain the various comparison operators in bash:
这些页面解释了 bash 中的各种比较运算符:
- http://www.tech-recipes.com/rx/209/bournebash-shell-scripts-string-comparison/
- http://tldp.org/LDP/abs/html/comparison-ops.html
- http://www.faqs.org/docs/Linux-HOWTO/Bash-Prog-Intro-HOWTO.html#ss11.2
- http://www.tech-recipes.com/rx/209/bournebash-shell-scripts-string-comparison/
- http://tldp.org/LDP/abs/html/comparison-ops.html
- http://www.faqs.org/docs/Linux-HOWTO/Bash-Prog-Intro-HOWTO.html#ss11.2
On the second linked page, you will find:
在第二个链接页面上,您会发现:
==
is equal to
if [ "$a" == "$b" ]
This is a synonym for =.
回答by John Giotta
The single equal is correct
单等号是正确的
string1 == string2
string1 = string2
True if the strings are equal. ‘=' should be used with the test command for POSIX conformance
字符串 1 == 字符串 2
字符串 1 = 字符串 2
如果字符串相等,则为真。'=' 应与测试命令一起用于 POSIX 一致性
NAME="rafael"
USER="rafael"
if [ "$NAME" = "$USER" ]; then
echo "Hello"
fi
回答by bash-o-logist
回答by Finer Recliner
In general, the = operator works the same as == when comparing strings.
通常,在比较字符串时,= 运算符的作用与 == 相同。
Note: The == comparison operator behaves differently within a double-brackets test than within single brackets.
注意: == 比较运算符在双括号测试中的行为与在单括号中不同。
[[ $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).