Issue
Just wondered if there was a simple way in bash scripting to use the 'test' construct to compare two strings matching a given pattern. In this particular case, I want a pair of numeric strings to match if they have leading zeros in front of either of them. Thanks.
#!/bin/bash
STR1=123
STR2=00123
if [[ "0*${STR1}" == "0*${STR2}" ]]; then
echo "Strings are equal"
else
echo "Strings are NOT equal"
fi
exit 0
Solution
If you are absolutely sure your strings are numeric, then you should use -eq
instead of ==
:
if [ $string1 -eq $string2 ]
then
echo "These are equal"
fi
The -eq
doesn't care about leading zeros
The problem is that if neither string is numeric (or one string is equal to zero and the other isn't numeric), this will still work:
string1=foo
string2=bar
if [ $string1 -eq $string2 ]
then
echo "These are equal" # This will print, and it shouldn't!
fi
The only way I see getting around this issue is to do something like this:
if expr $string1 + 0 > /dev/null 2&1 && expr $string2 + 0 > /dev/null 2>&1
then # Both strings are numeric!
if [ $string1 -eq $string2 ]
then
echo "Both strings are numeric and equal."
else
echo "Both strings are numeric, but not equal."
elif [ $sring1 = $sring2 ]
then
echo "Strings aren't numeric, but are the same
else
echo "Strings aren't numeric or equal to each other"
fi
The expr
will return a non-zero exit code if the string isn't numeric. I can use this in my if
to test to see if my strings are in fact numeric or not.
If they are both numeric, I can use my second if
with the -eq
to test for integer equivalency. Leading zeros are no problem.
The elif
is used in case my strings are not numeric. In that case, I test with =
which tests string equivalency.
Answered By - David W. Answer Checked By - Mildred Charles (WPSolving Admin)