如何用Shell判断邮件地址是否合法?

Bash

1 前言

一个问题,一篇文章,一出故事。
笔者最近需要通过Linux shell判断用户输入的邮件地址是否合法,于是整理此文。

2 基础知识

2.1 接收用户输入并判断邮箱合法性

2.1.1 创建脚本

cat > ~/scripts/checkMailRule.sh << EOF
#!/bin/bash

checkMailRule() {
        if [[ "$1" == ?*@?*.?* ]]; then
                return 0
        else
                return 1
        fi
}

read -p 'Please type e-mail address: ' email
if checkMailRule "$email"; then
        echo "$email <-- match email address rules"
else
        echo "$email <-- no match email address rules"
fi
EOF

2.1.2 测试脚本

sh ~/scripts/checkMailRule.sh

可见如下输入出,

Please type e-mail address: will@cmdschool.org
will@cmdschool.org <-- match email address rules

2.2 邮箱错误格式枚举

2.2.1 创建脚本

cat > ~/scripts/checkMailRule.sh << EOF
#!/bin/bash

checkMailRule() {
        if [[ "$1" == ?*@?*.?* ]]; then
                return 0
        else
                return 1
        fi
}

mailAddress="will@cmdschoolorg willcmdschool.org willcmdschoolorg will@ @cmdschool.org will@cmdschool.org"
for i in $mailAddress; do
        if checkMailRule "$i"; then
                echo "$i <-- match email address rules"
        else
                echo "$i <-- no match email address rules"
        fi
done
EOF

2.2.2 测试脚本

sh ~/scripts/checkMailRule.sh

可见如下输入出,

will@cmdschoolorg <-- no match email address rules
willcmdschool.org <-- no match email address rules
willcmdschoolorg <-- no match email address rules
will@ <-- no match email address rules
@cmdschool.org <-- no match email address rules
will@cmdschool.org <-- match email address rules

参阅文档
===================
https://haicoder.net/shell/shell-function-return.html
https://stackoverflow.com/questions/6524365/bash-if-comparison-to-force-a-valid-e-mail-address-format-is-entered

没有评论

发表回复

Bash
如何收集活跃的RHDS客户端IP地址?

1 前言 一个问题,一篇文章,一出故事。 笔者最近接到需要收集RHDS服务活跃的IP地址的工作任务, …

Bash
如何用Tigase监控postfix smtp服务?

1 前言 一个问题,一篇文章,一出故事。 笔者生产中的smtp服务器最近因为负载均衡器的路由故障而导 …

Bash
如何用Tigase监控Elasticsearch集群?

1 前言 一个问题,一篇文章,一出故事。 笔者生产中有一套Elasticsearch集群,笔者为了能 …