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._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$ ]] && echo "${BASH_REMATCH[1]}"
}
# This email id is wrong
emailid="tony@ironman"
# regex validation will fail
is_valid_email "$emailid" || echo "wrong email - $emailid"
correct_id="tony@iron.man" # Correct email id
is_valid_email "$correct_id" || echo "wrong email - $correct_id"