2017-08-04 7 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

関連する問題