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

Looping over read in bash until correct input is given

提问人:P_n 提问时间:8/4/2017 最后编辑:tripleeeP_n 更新时间:11/3/2023 访问量:3650

问:

将命令作为变量传递到提示符的正确方法是什么?例如,我有:

#!/bin/bash

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

我相信这可以循环,但我不知道如何。

Linux Bash

评论


答:

9赞 Eduard Itrich 8/4/2017 #1

只需将您的条件置于一个循环中,即只要您的条件不满足,就会从并要求适当的输入。whilereadstdin

#!/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赞 CuriousCase 11/10/2022
检查MAX_TRIES的轻微修改: #!/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 “输入IP地址: ” prompt while [ “$i” != “$prompt” -a “$t” -lt “$MAX_TRIES” ] ;do echo “错误的 IP 地址” t=“$((t+1))” read -p “输入 IP 地址: ” prompt if [ “$t” -eq “$MAX_TRIES” ] ;然后回显“输入错误太多”退出 1 fi 完成回显“正确的 IP,恭喜”退出 0