Bash Script to Validate Email Address with Regex
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ inside an if [[ $email =~ regex ]]; then condition to validate an email address.Examples
How to Think About It
if statement.Algorithm
Code
#!/bin/bash email="$1" regex='^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' if [[ $email =~ $regex ]]; then echo "Valid email address" else echo "Invalid email address" fi
Dry Run
Let's trace 'user@example.com' through the code
Input email
email='user@example.com'
Regex pattern
regex='^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
Match check
'user@example.com' matches regex -> true
| Step | Regex Match | |
|---|---|---|
| 1 | user@example.com | true |
Why This Works
Step 1: Regex pattern meaning
The regex ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ensures the email starts with allowed characters, has an '@', then a domain and a valid suffix.
Step 2: Using Bash regex match
The [[ $email =~ $regex ]] syntax tests if the email matches the pattern, returning true or false.
Step 3: Conditional output
If the match is true, the script prints 'Valid email address'; otherwise, it prints 'Invalid email address'.
Alternative Approaches
#!/bin/bash email="$1" if echo "$email" | grep -Eq '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'; then echo "Valid email address" else echo "Invalid email address" fi
#!/bin/bash email="$1" if perl -e 'exit($ARGV[0] =~ /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ ? 0 : 1)' "$email"; then echo "Valid email address" else echo "Invalid email address" fi
Complexity: O(n) time, O(1) space
Time Complexity
The regex match scans the email string once, so time complexity is linear in the length of the email.
Space Complexity
The script uses a fixed amount of memory for variables and regex, so space complexity is constant.
Which Approach is Fastest?
Bash's built-in regex matching is fastest; grep and Perl add overhead by calling external programs.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash regex match | O(n) | O(1) | Simple scripts, fast execution |
| grep with regex | O(n) | O(1) | Compatibility with older Bash versions |
| Perl regex | O(n) | O(1) | Complex regex needs, powerful validation |