2017-08-04 67 views
0

您好,我想知道將命令作爲變量傳遞給提示的正確方法是什麼?例如,我有:在bash中循環讀取,直到給出正確的輸入

#!/bin/bash 
clear ; 
i=`ifconfig tap0 | awk '{print $2}' | egrep "([0-9]{1,3}[\.]){3}[0-9]{1,3}"` 

read -p "Enter your IP: " prompt 
     if [[ $prompt == i ]] 
    then 
     echo "Correct IP, congrats" 
    else 
read -p "Wrong IP, try again: " prompt 
     if [[ $prompt == i ]] 
    then 
     echo "Correct IP, congrats" 
    else 
     echo "Wrong IP for the second time, exiting." 
    exit 0 
fi 

我確信這可以循環,但我不知道如何。我開始使用bash腳本,所以我學習了骯髒的方式:) 謝謝

回答

2

只需從stdin把你的病情在while循環,也就是說,只要你的條件沒有被滿足,read,並要求適當輸入。

#!/bin/bash 
clear 
i=$(ifconfig tap0 | awk '{print $2}' | egrep "([0-9]{1,3}[\.]){3}[0-9]{1,3}") 
read -p "Enter IP address: " prompt 
while [ "$i" != "$prompt" ] ; do 
    echo "Wrong IP address" 
    read -p "Enter IP address: " prompt 
done 
echo "Correct IP, congrats" 

如果你想的錯誤輸入的最大金額後中止,添加計數器

#!/bin/bash 

MAX_TRIES="5" 

clear 
i="$(ifconfig tap0 | awk '{print $2}' | egrep "([0-9]{1,3}[\.]){3}[0-9]{1,3}")" 
t="0" 
read -p "Enter IP address: " prompt 
while [ "$i" != "$prompt" -a "$t" -lt "$MAX_TRIES" ] ; do 
    echo "Wrong IP address" 
    t="$((t+1))" 
    read -p "Enter IP address: " prompt 
done 

if [ "$t" -eq "$MAX_TRIES" ] ; then 
    echo "Too many wrong inputs" 
    exit 1 
fi 

echo "Correct IP, congrats" 
exit 0 
+0

是真棒。非常感謝你:) – Petr