Reputation: 6303
I'm trying to check if an input string contains parentheses, which are: ()[]{}
.
I wrote the following code:
#!/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
If the string contains any of these: []{}
then the output is correct but if the string contains ()
then I get an error:
-bash: syntax error near unexpected token `('
These are the things I've tried so far:
*['\(''\)']*
*['()']*
*[()]*
Any idea how it should be written?
Edit #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 ~]#
Upvotes: 3
Views: 3940
Reputation: 785581
You can use this glob
pattern with ()
and []
escaped inside [...]
:
[[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no"
Testing:
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
Upvotes: 4