38

I am trying to see if a string is part of another string in shell script (#!bin/sh).

The code i have now is:

#!/bin/sh
#Test scriptje to test string comparison!

testFoo () {
        t1=$1
        t2=$2
        echo "t1: $t1 t2: $t2"
        if [ $t1 == "*$t2*" ]; then
                echo "$t1 and $t2 are equal"
        fi
}

testFoo "bla1" "bla"

The result I'm looking for, is that I want to know when "bla" exists in "bla1".

Thanks and kind regards,

UPDATE: I've tried both the "contains" function as described here: How do you tell if a string contains another string in Unix shell scripting?

As well as the syntax in String contains in bash

However, they seem to be non compatible with normal shell script (bin/sh)...

Help?

2

1 Answer 1

82

When using == or != in bash you can write:

if [[ $t1 == *"$t2"* ]]; then
    echo "$t1 and $t2 are equal"
fi

Note that the asterisks go on the outside of the quotes and that the wildcard pattern must be on the right.

For /bin/sh, the = operator is for equality only, not pattern matching. You can use case for pattern matching though:

case "$t1" in
    *"$t2"*) echo t1 contains t2 ;;
    *) echo t1 does not contain t2 ;;
esac

If you're specifically targeting Linux, I would assume the presence of /bin/bash.

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

9 Comments

Thanks a bunch Glenn! very much appreciated! (and it's a linux environment, but very lightweight, and without /bin/bash so i really needed that /bin/sh version! - thanks again!)
Better than coping with case, use =~ operator: if [[ $t1 =~ %t2* ]]; the echo match; fi
@lef, for a regular expression, you want [[ $t1 =~ "$t2" ]]
@glenn, right, besides a typo (%t2 instead of $t2), sh actually may not support double brackets [[ ]]
Notice that order matters: the wilds cards need to be on the right hand side of the comparison... at least from my experience.
|

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.