Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash wildcard with variables inside an if statement

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
like image 797
hudac Avatar asked Feb 11 '23 23:02

hudac


1 Answers

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.

like image 142
gniourf_gniourf Avatar answered Feb 14 '23 00:02

gniourf_gniourf