2

I'm trying to check if string contains any wildcards. Here is my failing attempt:

#!/bin/bash
WILDCARDS='* . ? !  ] [' 
a="foo*bar"
for x in $REJECTED_WILDCARDS
do 
    if [[ "$a" == *"$x"* ]]
    then 
            echo "It's there!";
    fi 
done

Any suggestions?

1
  • 2
    Why is . included in the list? Commented Apr 23, 2013 at 15:57

2 Answers 2

5

Slightly shorter and without a loop:

if [ "$a" != "${a//[\[\]|.? +*]/}"  ] ; then
  echo "wildcard found"
fi

The parameter substitution deletes all wildcards. The strings are than no longer equal.

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

1 Comment

I like this approach better.
4

Set wildcards into a bash array, like so

wildcards=( '*' '.' '?' '|' ']' '[' )

Then

a="foo*bar"
for wildcard in "${wildcards[@]}";
do
  if [[ $a == *"${wildcard}"* ]];
  then
    echo 'yes';
  fi;
 done

2 Comments

Great, this is what I've been looking for. Out of curiosity how do I add single quote to this list?
@user52028778, use double-quotes to quote it, like this: wildcards=( '*' '.' '?' '|' ']' '[', "'" )

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.