2014-10-20 109 views
1

在我寫的許多腳本,我使用的是非常具體的if statements並運行該腳本的用戶提供了2個或多個選項以供選擇,像我的一個腳本,這個例子部分:Shell腳本:如果用戶鍵入意外值,如何重複上次查詢?

read -r -p "How would you like to configure the NRPE daemon? [X]inetd/Standalone [D]aemon " DMN 
if [[ "$DMN" = [Xx] ]];   
    then 
    DMNMODE="xinetd" 
    cat <<EOF> $XINETDFILE 
service nrpe 
{ 
     flags   = REUSE 
     type   = UNLISTED 
     port   = $NRPEPORT 
     socket_type  = stream 
     wait   = no 
     user   = $NGUSER 
     group   = $NGGROUP 
     server   = /usr/sbin/nrpe 
     server_args  = -c $NRPECFG --inetd 
     log_on_failure += USERID 
     disable   = no 
     only_from  = 127.0.0.1 $NAGIOSSRV 
} 
EOF 
    $XINETDSVC restart 
elif [[ "$DMN" = [Dd] ]]; 
    then 
    chkconfig nrpe on ; $NRPESVC start 
    DMNMODE="daemon" 
fi 

如果用戶鍵入其中一個期望值,那麼一切都可以,腳本按預期工作,但如果其中一個答案中有拼寫錯誤,並且腳本獲取了值,則不知道該腳本退出。 我想確保在出現錯字時用戶不會被踢出腳本......我在想,如果插入錯字,那麼用戶會被問到最後一個問題。 我知道這可以通過使用Case來實現,但我正在尋找更好的解決方案,您能否幫助我? 在此先感謝

回答

1

這是諸如此類的事情了select內置的是有用的:

select DMN in 'Xinetd' 'Standalone Daemon'; do 
    if [[ "$DMN" = [Xx] ]]; then 
     .... 
     break 
    elif [[ "$DMN" = [Dd] ]]; then 
     ... 
     break 
    fi 
done 

然後,只需檢查DMN值,並打破當你有一個有效值,剝落結束的循環會自動再次提示。

+0

這正是我尋找的更復雜的方式,謝謝! – 2014-10-20 19:04:58

1

檢查,如果這是你所需要的:

while [ 1 ] 
do 
read -r -p "How would you like to configure the NRPE daemon? [X]inetd/Standalone [D]aemon " DMN 
if [[ "$DMN" = [Xx] ]];   
    then 
    DMNMODE="xinetd" 
    cat <<EOF> $XINETDFILE 
service nrpe 
{ 
     flags   = REUSE 
     type   = UNLISTED 
     port   = $NRPEPORT 
     socket_type  = stream 
     wait   = no 
     user   = $NGUSER 
     group   = $NGGROUP 
     server   = /usr/sbin/nrpe 
     server_args  = -c $NRPECFG --inetd 
     log_on_failure += USERID 
     disable   = no 
     only_from  = 127.0.0.1 $NAGIOSSRV 
} 
EOF 
    $XINETDSVC restart 
    break 
elif [[ "$DMN" = [Dd] ]]; 
    then 
    chkconfig nrpe on ; $NRPESVC start 
    DMNMODE="daemon" 
    break 
else 
    continue 
fi 
done 
+0

你能解釋一下嗎? – 2014-10-20 18:13:59

+0

這是一個無限循環,只要用戶輸入期望值,腳本就會完成應該完成的任務並從循環中斷開。如果用戶給出了除期望值以外的任何內容,那麼腳本將繼續向用戶提出問題(「您希望如何配置NRPE守護進程?...」)。 – 2014-10-20 18:16:48

+0

謝謝,看來這正是我需要的,這是處理這些情況的最複雜的方法嗎? – 2014-10-20 18:17:58

0

您可以使用while循環在你的if語句。

#!/bin/bash 

success=0 
while [ $success -lt 1 ]; do 
    read -r -p "How would you like to configure the NRPE daemon? [X]inetd/Standalone [D]aemon " DMN 
    if [[ "$DMN" = [Xx] ]]; 
     then 
      echo "option 1" 
      success=1 
    elif [[ "$DMN" = [Dd] ]]; 
     then 
      echo "option 2" 
      success=1 
    fi 
done