1

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?

2 Answers 2

3

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

Use:

[[ $modifiedOSVersion == *"$machineOSVersion"* ]] && echo "matched" || echo "nope"
Sign up to request clarification or add additional context in comments.

Comments

3

You've got the 2 variables in the comparison backwards. You have to write the conditional as follows:

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

You can think of this like that: ${modifiedOSVersion} is the largest of the two strings, so you need to add stuff to ${machineOSVersion} to match it. This additional stuff is represented here by the two *.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.