一段可以验证给定的IP地址字符串是否合法的bash脚本

#!/bin/bash
validate_ipaddress() {
  declare 
-i iPart1
  declare 
-i iPart2
  declare 
-i iPart3
  declare 
-i iPart4

  inputip
=$1
  
# validate it
  if [ -$inputip ]; then
    
return 1
  fi

  echo 
$inputip | grep --"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
  
if [ $? -ne 0 ]; then
    
return 1
  fi

  
# separate the ip address
  ippart1=${inputip%%.*}
  inputip
=${inputip#*.}
  ippart2=${inputip%%.*}
  inputip
=${inputip#*.}
  ippart3=${inputip%%.*}
  ippart4
=${inputip#*.}

  # check whether the ip number begins with zero, that is wrong syntax
  # if the string begins with zero, bash cannot convert it into integer correctly
  # ipart1 and ipart4 cannot be zero

  if echo $ippart1 | grep -"^0" || echo $ippart4 | grep -"^0"; then
    
return 1
  fi

  
if [ $ippart2 != "0" ] && echo $ippart2 | grep -"^0"; then
    
return 1
  fi

  
if [ $ippart3 != "0" ] && echo $ippart3 | grep -"^0"; then
    
return 1
  fi
         
  iPart1
=ippart1
  iPart2
=ippart2
  iPart3
=ippart3
  iPart4
=ippart4
  
if [ $iPart1 -gt 254 ] || [ $iPart2 -gt 254 ] || [ $iPart3 -gt 254 ] || [ $iPart4 -gt 254 ]; then
    
return 1
  fi

  
return 0
}

if validate_ipaddress $1; then
  echo 
"legal"
else
  echo 
"illegal"
fi

 注意在验证IP地址是否合法的RE中,使用了{m,n}这样的语法,这样写grep是要加-E option的,因为这是扩展语法,有些UNIX和Linux上的grep,不加-E(基本模式,非扩展模式)的时候也支持这个语法,但要写成\{m,n\}这样的样式

原文地址:https://www.cnblogs.com/super119/p/1910017.html