如果字符串变量包含通配符,如何检入shell脚本?

时间:2013-04-23 15:38:41

标签: bash shell wildcard

我正在尝试检查字符串是否包含任何通配符。 这是我失败的尝试:

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

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

稍短且没有循环:

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

参数替换删除所有通配符。 字符串不再相等。

答案 1 :(得分:4)

将通配符设置为bash数组,如此

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

然后

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