This question already has an answer here:
-
How to compare strings in Bash
10 answers
-
How do I compare two string variables in an 'if' statement in Bash? [duplicate]
12 answers
I am using SH shell and I am trying to compare a string with a variable's value but the if
condition is always execute to true. Why?
Here is some code:
Sourcesystem="ABC"
if [ "$Sourcesystem" -eq 'XYZ' ]; then
echo "Sourcesystem Matched"
else
echo "Sourcesystem is NOT Matched $Sourcesystem"
fi;
echo Sourcesystem Value is $Sourcesystem ;
Even this is not working:
Sourcesystem="ABC"
if [ 'XYZ' -eq "$Sourcesystem" ]; then
echo "Sourcesystem Matched"
else
echo "Sourcesystem is NOT Matched $Sourcesystem"
fi;
echo Sourcesystem Value is $Sourcesystem ;
Secondly, can we match this with a NULL or empty string?
You should use the =
operator for string comparison:
Sourcesystem="ABC"
if [ "$Sourcesystem" = "XYZ" ]; then
echo "Sourcesystem Matched"
else
echo "Sourcesystem is NOT Matched $Sourcesystem"
fi;
man test
says that you use -z
to match for empty strings.
-eq
is used to compare integers. Use =
instead.
I had this same problem, do this
if [ 'xyz' = 'abc' ];
then
echo "match"
fi
Notice the whitespace. It is important that you use a whitespace in this case after and before the =
sign.
Check out "Other Comparison Operators".
eq is used to compare integers use equal '=' instead ,
example:
if [ 'AAA' = 'ABC' ];
then
echo "the same"
else
echo "not the same"
fi
good luck
-eq
is the shell comparison operator for comparing integers. For comparing strings you need to use =
.
-eq
is a mathematical comparison operator. I've never used it for string comparison, relying on ==
and !=
for compares.
if [ 'XYZ' == 'ABC' ]; then # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
echo "Match"
else
echo "No Match"
fi
Of the 4 shells that I've tested, ABC -eq XYZ
evaluates to true in the test
builtin for zsh
and ksh
. The expression evaluates to false under /usr/bin/test
and the builtins for dash
and bash
. In ksh
and zsh
, the strings are converted to numerical values and are equal since they are both 0. IMO, the behavior of the builtins for ksh
and zsh
is incorrect, but the spec for test
is ambiguous on this.