如何检查字符串是否包含括号“)(”?

How to check if a string contains brackets ")("?

我正在尝试检查输入字符串是否包含括号,它们是:()[]{}.

我写了下面的代码:

#!/bin/bash
str=""
if [ -z "$str" ]; then
  echo "Usage: $(basename [=10=]) string"
  exit 1
fi
if [[ "$str" == *['\{''}''\[''\]''('')']* ]];
then
  echo "True"
else
  echo "False"
fi

如果字符串包含以下任何一项:[]{} 那么输出是正确的,但是如果字符串包含 () 那么我会得到一个错误:

-bash: syntax error near unexpected token `('

这些是我到目前为止尝试过的东西:

*['\(''\)']*
*['()']*
*[()]*

知道应该怎么写吗?

编辑 #1:

[root@centolel ~]# date
Tue Nov  3 18:39:37 IST 2015
[root@centolel ~]# bash -x asaf.sh {
+ str='{'
+ '[' -z '{' ']'
+ [[ { == *[{}\[\]\(\)]* ]]
+ echo True
True
[root@centolel ~]# bash -x asaf.sh (
-bash: syntax error near unexpected token `('
[root@centolel ~]#

您可以使用此 glob 模式,其中 ()[][...]:

内转义
[[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"

测试:

str='abc[def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abc}def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abc[def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abc(def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abc)def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abc{}def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abc}def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
yes

str='abcdef' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
no