Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regex matching operator in bourne shell script?

Tags:

shell

unix

sh

I am trying to validate user input against a regular expression.

vari=A
if [ $vari =~ [A-Z] ] ;
then
    echo "hurray"
fi

The output I am getting is swf.sh[3]: =~: unknown test operator.

Can you please let me know the test operator I can use?

like image 905
Adivya Yadav Avatar asked Dec 02 '22 15:12

Adivya Yadav


2 Answers

It's not built into Bourne shell, you need to use grep:

if echo "$vari" | grep -q '[A-Z]'; then
    echo hurray
fi

If you want to match the whole string, remember to use the regex anchors, ^ and $. Note that the -q flag makes grep quiet, so its only output is the return value, for match/not match.

like image 97
piojo Avatar answered Dec 06 '22 21:12

piojo


POSIX shell doesn't have a regular expression operator (or rather, the POSIX test command does not). Instead, you use the expr command to do a (limited) form of regular expression matching.

if expr "$vari" : '[A-Z]' > /dev/null; then

(I say "limited" because it always matches at the beginning of the string, as if the regular expression started with ^.) The exit status is 0 if a match is made; it also writes the number of characters matched to standard output, hence the redirect to /dev/null.

If you are actually using bash, you need to use the [[ command:

if [[ $vari =~ [A-Z] ]]; then
like image 43
chepner Avatar answered Dec 06 '22 21:12

chepner