Operations, shell scripts often encounter the legitimacy of determining the value entered, such as IP, email address, and so on. Then, according to their own script to summarize the judgment of IP legitimacy script to share to the netizen, when encountered can be a reference.
Idea: IP consists of four-bit numbers, divided by points, each field cannot be greater than 255, must conform to this format
Method 1:
Function check_ip () { ip=$1 valid_check=$ (echo $ ip|awk -f. ' $1<=255&&$2<=255&&$3<=255&&$4<=255{print "Yes"} ') if echo $IP |grep -e "^[0-9]{1,3}\. [0-9] {1,3}\. [0-9] {1,3}\. [0-9] {1,3}$ ">/dev/null; then if [ $VALID _check == "Yes" ]; then echo "$IP available." else echo "$IP not available!" fi else echo "$IP not available!" fi}# examplecheck_ip 192.168.1.1check_ip 256.1.1.1
Blog Address:http://lizhenliang.blog.51cto.com
Method 2:
FUNCTION&NBSP;CHECK_IP () { IP=$1 if [[ $IP = ~ ^[0-9]{1,3}\. [0-9] {1,3}\. [0-9] {1,3}\. [0-9] {1,3}$ ]]; then field1=$ (echo $IP |cut -d. &NBSP;-F1) field2=$ (echo $IP |cut -d. -f2) field3=$ (echo $IP |cut -d. -f3) field4=$ (echo $IP |cut -d. -f4) if [ $FIELD 1 -le 255 -a $FIELD 2 -le 255 -a $FIELD 3 -le 255 -a $FIELD 4 -le 255 ]; then echo "$IP available." else echo "$IP not available!" fi else echo "$IP not available!" fi}# examplecheck_ip 192.168.1.1check_ip 256.1.1.1
Add a loop if the error is re-entered until it is correct:
Function check_ip () { local ip=$1 valid_check=$ ( echo $IP |awk -f. ' $1<=255&&$2<=255&&$3<=255&&$4<=255{print "Yes"} ') if echo $IP |grep -e "^[0-9]{1,3}\. [0-9] {1,3}\. [0-9] {1,3}\. [0-9] {1,3}$ " >/dev/null; then if [ $VALID _ check == "yes" ]; then echo "$IP available! " return 0 else echo "$IP not available!" return 1 fi else echo "$IP not available!" return 1 fi}while true; do read -p "please enter ip: " IP check_ip $IP [ $? -eq 0 ] && break | | continuedone
This article is from the "Li Zhenliang Technology Blog" blog, make sure to keep this source http://lizhenliang.blog.51cto.com/7876557/1736160
Shell script determines whether IP is legitimate