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

时间:2015-11-03 16:26:05

标签: string bash shell escaping

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

我写了以下代码:

#!/bin/bash
str="$1"
if [ -z "$str" ]; then
  echo "Usage: $(basename $0) 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 ~]#

1 个答案:

答案 0 :(得分:4)

您可以使用此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