Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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??

like image 898
ballstud Avatar asked Jan 26 '10 10:01

ballstud


People also ask

How to validate email address using regular expression?

Requirement 1: Email address field should mandate with “@” symbol and should have “. (dot)” at any place after @ symbol and can end with any type of domain. Example: [email protected] or [email protected] or [email protected] Below is the explanation for the above to be configured regular expression. we are going to use it on rule to validate email address.

How do I check if an email address is grammatically correct?

If you only want to check if an address is grammatically correct then you could use a regular expression, but note that ""@ [] is a grammatically correct email address that certainly doesn't refer to an existing mailbox. The syntax of email addresses has been defined in various RFCs, most notably RFC 822 and RFC 5322.

How can I validate the format of an email address?

Here are four regular expressions (often called regexes) that all validate the format of an email address. They have increasing degrees of complexity. The more complicated, the more accurate each is at matching only email addresses. 1. Dirt-simple approach Here's a regex that only requires a very basic [email protected]: Upside: Dirt simple.

What are the regexes for matching old email addresses?

This means that the regexes only match email addresses that are strictly RFC 5322 compliant. If you have to match "old" addresses (as the looser grammar including the "obs-" rules does), you can use one of the RFC 822 regexes from the previous paragraph.


1 Answers

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
like image 63
Peter Eisentraut Avatar answered Nov 18 '22 13:11

Peter Eisentraut