shell 函数实现检测字符串是否为合法的 IPv4 地址

前端之家收集整理的这篇文章主要介绍了shell 函数实现检测字符串是否为合法的 IPv4 地址前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

导语: 此 shell 函数仅以记录之前的劳动果实,并分享给他人,个人原创,欢迎使用并给予 bug 的反馈.

#!/bin/bash
 isLegalIPv4 ()
 {
   local myLocation=${FUNCNAME}
   local isStrict=@H_502_14@0
   local s=
   function usage ()
   {
     echo -e "\nUsage:\n ${myLocation} [-h]|[-s] IP1[,IP2,...]\n"
     echo -e " -s,开启严格模式,此时若某个非零数字前面有前缀0时该IP无效"
     echo -e " -h,输出此说明方式\n"
   }
   function hasNotPrefixZero ()
   {
     local x=
     for x in $(echo $@ | sed 's/\./ /g')
     do
       [ "${x:0:1}" == "0" ] && [ $x -ne @H_502_14@0 ] && return @H_502_14@1
     done
     return @H_502_14@0
   }
   function isDigitCharAll ()
   {
     echo $1 | sed 's/\.//g' | grep -E "^[0-9]+$" >&/dev/null
     return $?
   }
   function checkNumberRange ()
   {
     local arr=($(echo $1 | sed 's/\./ /g'))
     if [ ${#arr[@]} -ne @H_502_14@4 ]; then
       echo "$1 不是合法的 IPv4 地址.合法的 IPv4 地址只能 有3个分割符'.'"
       return @H_502_14@1
     fi
     if [ ${arr[0]} -eq @H_502_14@0 ]; then
       echo "$1 不是合法IPv4地址. 因为它包含超出范围的数字段(第1段的范围是: 1~255; 第2/3/4段的范围: 0~255)."
       return @H_502_14@1
     fi
     for x in ${arr[@]}
     do
       if [ $x -gt @H_502_14@255 ]; then
         echo "$1 不是合法IPv4地址. 因为它包含超出范围的数字段(第1段的范围是: 1~255; 第2/3/4段的范围: 0~255)."
         return @H_502_14@1
       fi
     done
     return @H_502_14@0
   }
   [ $# -eq @H_502_14@0 ] && usage && return
   [ $# -ge @H_502_14@1 ] && [ "x$1" == "x-h" -o "x$1" == "x-H" ] && usage && return
   [ $# -ge @H_502_14@1 ] && [ "x$1" == "x-s" -o "x$1" == "x-S" ] && isStrict=@H_502_14@1 && shift
   for s in $(echo $@ | sed 's/,/ /g')
   do
     isDigitCharAll $s
     [ $? -ne @H_502_14@0 ] && echo "$s 不是合法 IPv4 地址. 因为它包含非数字字符(分隔符'.'除外)" && continue
     checkNumberRange $s
     [ $? -ne @H_502_14@0 ] && continue
     if [ $isStrict -eq @H_502_14@1 ]; then
       hasNotPrefixZero $s
       [ $? -ne @H_502_14@0 ] && echo "$s 不是合法 IPv4 地址. 当前为严格模式,同时它含有前缀0的数字段." && continue
     fi
     echo "$s 是合法 IPv4 地址."
   done
 }
原文链接:https://www.f2er.com/bash/390412.html

猜你在找的Bash相关文章