2014-05-15 113 views
0

我对bash脚本非常陌生,所以基本上我无法理解它,所以请任何人都能告诉我可以更快学习的方法。使用bash脚本验证IP地址

我是tryong写一个bash脚本来读取ip地址并验证它。 所以,请你能告诉我在我使用的剧本中我犯了什么错误。

function valid_ip() 
{ 
    local IPA1=$1 
    local stat=1 

    if [[ $IPA1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; 
    then 
     OIFS=$IFS 
     IFS='.' 
     ip=($ip) 
     IFS=$OIFS 

     [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ 
      && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] 
     stat=$? 
    fi 
    return $stat 
} 

此代码我也从互联网本身只是为了理解的概念,但我仍然无法得到它。

+0

哪部分你不明白? – choroba

+0

放在那之后的零件 – user3639779

+1

你有没有在'man bash'里看过IFS? – choroba

回答

0

请阅读评论:

function valid_ip() 
{ 
    local IPA1=$1 
    local stat=1 

    if [[ $IPA1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; 
    then 
     OIFS=$IFS 

    IFS='.'    #read man, you will understand, this is internal field separator; which is set as '.' 
     ip=($ip)  # IP value is saved as array 
     IFS=$OIFS  #setting IFS back to its original value; 

     [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ 
      && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] # It's testing if any part of IP is more than 255 
     stat=$? #If any part of IP as tested above is more than 255 stat will have a non zero value 
    fi 
    return $stat # as expected returning 

您可以通过printf '%q' $IFS将其设置为任何其他值之前检查IFS的默认值。

+0

非常感谢.... – user3639779

+0

很高兴我可以帮助你! – PradyJord

0
function valid_ip() 
{ 
    local IPA1=$1 
    local stat=1 

    if [[ $IPA1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; 
    then 
     OIFS=$IFS # Save the actual IFS in a var named OIFS 
     IFS='.' # IFS (Internal Field Separator) set to . 
     ip=($ip) # ¿Converts $ip into an array saving ip fields on it? 
     IFS=$OIFS # Restore the old IFS 

     [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] # If $ip[0], $ip[1], $ip[2] and $ip[3] are minor or equal than 255 then 

     stat=$? # $stat is equal to TRUE if is a valid IP or FALSE if it isn't 

    fi # End if 

    return $stat # Returns $stat 
}