Skip to content
Advertisement

Bash if condition doesn’t match when comparing particular string

Bash if condition doesn’t match when comparing particular string

Matching string:

Red Hat Enterprise Linux Server release 7.2 (Maipo)

Code:

machineOSVersion="Red Hat Enterprise Linux Server release 7.2 (Maipo)"

modifiedOSVersion="CentOS Linux release 7 OR Red Hat Enterprise Linux Server release 7.2 (Maipo)"

if [[ ${machineOSVersion} = *"${modifiedOSVersion}"* ]]; then

    echo -e "match"

else

    echo -e "doesn't match"

fi

I expected this to match, but it does not.

The same code works with other strings. Is this failing because of ( or ) character in the string?

Advertisement

Answer

You have variable matching reversed. You have to use * matching around subset variable not the superset variable.

Use:

[[ $modifiedOSVersion == *"$machineOSVersion"* ]] && echo "matched" || echo "nope"
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement