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?
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With