Question

I have used a preg_match based 'regex' in a php script that I use. The regex is ^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$

How can I incorporate this in a bash conditional to test Email addresses for basic structure? My email address is in a file called 'email'. (It is looped through as required). Like if [cat email | '/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/' ]; then { or whatever. I have no idea how to write this. Can anyone help...

Was it helpful?

Solution

Using your regular expression and adapting it to bash to test an address held in the variable email:

#!/bin/bash
if [[ $email =~ ^[[:alnum:]_.-]+@[[:alnum:]_.-]+\.[[:alpha:]]{2,6}$ ]]
then
    echo "Good address"
else
    echo "Bad address"
fi

Notes:

  • this uses the [[...]] construct so an ordinary POSIX shell won't do: bash or better is required.

  • The =~ operator matches a string, in this case the email address, to a POSIX Extended Regular Expression.

  • The actual spec for email addresses, (have a look at RFC5322), is very complex (see this sample but outdated regex) and your regex is only an approximation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top