1

Please help.

I'm trying to compare string1 against string2 in a Bash script.

I can do the easy bit of:-

if [[ $string1 == $string2 ]]
then    
    yippee    
fi

What I'm having trouble with is the syntax for when

"the$string1" == $string2  or "a$string1" == $string2

or

 $string1 == the$string2 or $string1 == a$string2

I assume it's something like:-

if [[ $string1 == $string2 || "(a|the)$string1" == $string2 || $string1 == "(a|the)$string2" ]]

But it's not and I cannot seem to find the answer. (I'm obviously asking the wrong question!)

Thanks for any help.

PS I'd rather not use any external progs such as awk etc.

2

1 Answer 1

0

You might want:

if [[ $string1 == *"$string2"* ]]; then
    echo "string1 contains string2"

elif [[ $string2 == *"$string1"* ]]; then
    echo "string2 contains string1"
fi

Within [[...]] the == operator is a pattern matching operator.

Ref: 6.4 Bash Conditional Expressions


For specifically an optional "a" or "the" prefix:

[[ $string1 == ?(a|the)"$string2" || $string2 == ?(a|the)"$string1" ]]

That uses bash's extended patterns, see 3.5.8.1 Pattern Matching

Sign up to request clarification or add additional context in comments.

1 Comment

Note that the variable on the right-hand side is quoted: that is to treat it as literal text, in case the variable's contents contain shell globbing characters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.