2014-05-15 116 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 
}