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
没有评论