Checking correctness of an email address with a regular expression in Bash
bash, email-validation, regex, shell
Solution
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="test@terra.es"
if [[ $i =~ $regex ]] ; then
echo "OK"
else
echo "not OK"
fi
Problem
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="test@terra.es" 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??