7

I want to find substring in a string according to this solution.

But for some reason it doesn't work with variables:

str="abcd";
substr="abc";
if [[ "${substr}"* == ${str} ]]
then
        echo "CONTAINS!";
fi
Community
  • 1
  • 1
hudac
  • 2,584
  • 6
  • 34
  • 57

1 Answers1

13

In the reference manual, section Conditional Constructs, you will read, for the documentation of [[ ... ]]:

When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching, as if the extglob shell option were enabled.

(emphasize is mine).

So you need to put your glob pattern to the right of the == operator:

if [[ $str == "$substr"* ]]; then

Note that the left-hand side needs not be quoted, but the part $substr of the right-hand side needs to be quoted, in case it contains glob characters like *, ?, [...], +(...), etc.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104