Linux shell programming string compare syntax

北慕城南 提交于 2019-12-04 16:07:54

问题


What is the difference between = and == to compare strings in Linux shell programming?

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?


回答1:


These pages explain the various comparison operators in 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

On the second linked page, you will find:

==

    is equal to

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

    This is a synonym for =.



回答2:


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

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



回答3:


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

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




回答4:


you can take a look here or here. Personally, to compare strings, I use case

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

I do not have to know which operator i should use



来源:https://stackoverflow.com/questions/5745303/linux-shell-programming-string-compare-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!