[Code Example] Check if string is valid email id in bash script

Total
0
Shares

In this article we will provide you bash script code to check if a string is a valid email id or not. There is a predefined format of email ids and every id should follow that. It’s good to verify the correctness of id before saving them in databases.

Code Example –

#!/bin/bash
is_valid_email() {
    [[ $1 =~ ^([a-zA-Z0-9._%-][email protected][a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$ ]] && echo "${BASH_REMATCH[1]}"
}

# This email id is wrong
emailid="[email protected]"

# regex validation will fail
is_valid_email "$emailid" || echo "wrong email - $emailid"

correct_id="[email protected]" # Correct email id
is_valid_email "$correct_id" || echo "wrong email - $correct_id"

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like