Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell programming string compare syntax

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?

like image 759
john Avatar asked Apr 21 '11 14:04

john


People also ask

How would you compare the strings in a shell script?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What is the syntax to compare to string?

Syntax: str1.equals(str2); Here str1 and str2 both are the strings which are to be compared. Using String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string.

Can you compare strings in bash?

The need to compare strings in a Bash script is relatively common and can be used to check for certain conditions before proceeding on to the next part of a script. A string can be any sequence of characters. To test if two strings are the same, both strings must contain the exact same characters and in the same order.

What is string comparison in Linux?

String Comparison means to check whether the given strings are the same or not. Two or more strings are the same if they are of equal length and contain the same sequence of characters. Equality operator used with [ command and returns true if both operands are equal.


2 Answers

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
like image 183
John Giotta Avatar answered Oct 29 '22 22:10

John Giotta


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

like image 29
Finer Recliner Avatar answered Oct 29 '22 22:10

Finer Recliner