2016-08-17 47 views
0

我一直在玩bash腳本40天,有0經驗,所以原諒我,如果我的代碼看起來像廢話。我有一個腳本,如果你想用的情況下進行更改,將採取配置的NTP服務器出/etc/ntp.conf中的文件(/root/ntp.conf用於測試)Bash For Loop With If Elif Logic Broken

NTPSRVCounter=1 
echo "--- NTP Configuration ---" 
echo " " 
while read -r line; do 
    if [ $NTPSRVCounter == 1 ] ; then 
     echo "Primary NTP: $line" 
     SEDConfiguredNTP1="$(echo $line | sed 's/\./\\./g')" 
     ((NTPSRVCounter++)) 
     echo " " 
      else 
     SEDConfiguredNTP2="$(echo $line | sed 's/\./\\./g')" 
     echo "Secondary NTP: $line" 
     echo "" 
    fi 
    done < <(grep -o -P '(?<=server).*(?= iburst)' /root/ntp.conf) 

,並問你聲明:

echo "Do you wish to change it? [Y/n]" 
NTPSRVCounter2=1 
read opt 
case $opt in 
    Y|y) read -p "Enter in your primary NTP server: " -e -i '0.debian.pool.ntp.org' UserInputNTP1 
    read -p "Enter in your secondary NTP serer: " -e -i '1.debian.pool.ntp.org' UserInputNTP2 
    for NTP in "$UserInputNTP1" "$UserInputNTP2" ; do 
     is_fqdn "$NTP" 
      if [[ $? == 0 && $NTPSRVCounter2 == 1 ]] ; then 
       SEDUserInput1=$(echo $UserInputNTP1 | sed 's/\./\\./g') 
       ((NTPSRVCounter2++)) 
      elif [[ $? == 0 && $NTPSRVCounter2 == 2 ]] ; then 
       SEDUserInput2=$(echo $UserInputNTP2 | sed 's/\./\\./g') 
       sudo sed -i "s/$SEDConfiguredNTP1/$SEDUserInput1/g" /root/ntp.conf 
       sudo sed -i "s/$SEDConfiguredNTP2/$SEDUserInput2/g" /root/ntp.conf 
      else 
       echo "Fail!!! :-(" 
      fi 
     done 

    ;; 

    N|n) return 0 

    ;; 

    *) echo "I don't know what happened, but, eh, you're not supposed to be here." 
    ;; 
    esac 

問題是在函數的第二次運行中使用「elif」語句和函數「is_fqdn」。如果我在腳本上放置了「bash -x」並運行它,我看到「is_fqdn」在函數的兩次運行中都返回0,但elif語句「$?」即將達到1而不是0.

使用的兩個函數如下。必須驗證NTP地址是有效的域名還是I.P.地址,對吧? :)

is_fqdn() { 
hostname=$1 
if [[ "$hostname" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then 
    valid_ip "$hostname" 
elif [[ "$hostname" == *"."* && "$hostname" != "localhost." && "$hostname" != "localhost" ]] ; then 
    return 0 
else 
    return 1 
fi 
host $hostname > /dev/null 2>&1 || return 1 
} 


valid_ip(){ 
local stat=1 
local ip=$1 
if [[ $ip =~ ^[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" 
} 

回答

1

條件在if$?的價值,這是何等的使用條件在elif部分,而不是is_fqdn返回值。如果要在多個位置使用該值,則需要保存該值:

is_fqdn "$NTP" 
is_fqdn_rv=$? 
if [[ $is_fqdn_rv == 0 && $NTPSRVCounter2 == 1 ]] ; then 
    SEDUserInput1=$(echo $UserInputNTP1 | sed 's/\./\\./g') 
    ((NTPSRVCounter2++)) 
elif [[ $is_fqdn_rv == 0 && $NTPSRVCounter2 == 2 ]] ; then 
    SEDUserInput2=$(echo $UserInputNTP2 | sed 's/\./\\./g') 
    sudo sed -i "s/$SEDConfiguredNTP1/$SEDUserInput1/g" /root/ntp.conf 
    sudo sed -i "s/$SEDConfiguredNTP2/$SEDUserInput2/g" /root/ntp.conf 
else 
    echo "Fail!!! :-(" 
fi 
+0

謝謝!!!!這工作!學到了一些東西! – emdk