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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16173569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:15:28  来源:igfitidea点击:

How to check in shell script if string variable contains a wildcard?

bashshellwildcard

提问by user52028778

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?

有什么建议?

回答by Fritz G. Mehner

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.

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

回答by iruvar

Set wildcards into a bash array, like so

将通配符设置为 bash 数组,就像这样

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

Then

然后

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