Shell脚本判断IP是否合法性(多种方法)
运维角度来说,写shell脚本经常会遇到判断输入的值是否合法,比如IP、邮件地址等。那么,根据自身写脚本中总结的判断IP合法性脚本分享给网友,遇到时能有所参考。
思路:IP由四位数字组成,以点分割,每个字段不能大于255,必须符合这种格式
方法1:
#!/bin/bash#blog:http://lizhenliang.blog.51cto.comfunctioncheck_ip(){IP=$1VALID_CHECK=$(echo$IP|awk-F.'$1<=255&&$2<=255&&$3<=255&&$4<=255{print"yes"}')ifecho$IP|grep-E"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$">/dev/null;thenif[${VALID_CHECK:-no}=="yes"];thenecho"IP$IPavailable."elseecho"IP$IPnotavailable!"fielseecho"IPformaterror!"fi}#Examplecheck_ip192.168.1.1check_ip256.1.1.1
方法2:
#!/bin/bash#blog:http://lizhenliang.blog.51cto.comfunctioncheck_ip(){IP=$1if[[$IP=~^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$]];thenFIELD1=$(echo$IP|cut-d.-f1)FIELD2=$(echo$IP|cut-d.-f2)FIELD3=$(echo$IP|cut-d.-f3)FIELD4=$(echo$IP|cut-d.-f4)if[$FIELD1-le255-a$FIELD2-le255-a$FIELD3-le255-a$FIELD4-le255];thenecho"IP$IPavailable."elseecho"IP$IPnotavailable!"fielseecho"IPformaterror!"fi}#Examplecheck_ip192.168.1.1check_ip256.1.1.1
加个循环,如果错误则重新输入,直到正确:
#!/bin/bash#blog:http://lizhenliang.blog.51cto.comfunctioncheck_ip(){localIP=$1VALID_CHECK=$(echo$IP|awk-F.'$1<=255&&$2<=255&&$3<=255&&$4<=255{print"yes"}')ifecho$IP|grep-E"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$">/dev/null;thenif[$VALID_CHECK=="yes"];thenecho"IP$IPavailable!"return0elseecho"IP$IPnotavailable!"return1fielseecho"IPformaterror!"return1fi}whiletrue;doread-p"PleaseenterIP:"IPcheck_ip$IP[$?-eq0]&&breakdone
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。