Checking correctness of an email address with a regular expression in Bash

ballstud picture ballstud · Jan 26, 2010 · Viewed 33.6k times · Source

I'm trying to make a Bash script to check if an email address is correct.

I have this regular expression:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Source: http://www.regular-expressions.info/email.html

And this is my bash script:

regex=[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

i="[email protected]"
if [[ $i=~$regex ]] ; then
    echo "OK"
else
    echo "not OK"
fi

The script fails and give me this output:

10: Syntax error: EOF in backquote substitution

Any clue??

Answer

Peter Eisentraut picture Peter Eisentraut · Jan 26, 2010

You have several problems here:

  • The regular expression needs to be quoted and special characters escaped.
  • The regular expression ought to be anchored (^ and $).
  • ?: is not supported and needs to be removed.
  • You need spaces around the =~ operator.

Final product:

regex="^[a-z0-9!#\$%&'*+/=?^_\`{|}~-]+(\.[a-z0-9!#$%&'*+/=?^_\`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]*[a-z0-9])?\$"

i="[email protected]"
if [[ $i =~ $regex ]] ; then
    echo "OK"
else
    echo "not OK"
fi