循环读取bash,直到给出正确的输入

时间:2017-08-04 02:01:39

标签: linux 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脚本,所以我正在学习肮脏的方式:) 谢谢

1 个答案:

答案 0 :(得分:2)

只需将您的条件置于while循环中,即只要您的条件不满意,read stdin并请求正确的输入。

#!/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