使用 read 的无限 while 循环问题

使用 read 的无限 while 循环问题

我正在编写一个小脚本,要求用户插入 1-10 之间的数字。然后,脚本将告诉用户该数字是否在请求的值之间,并从那里继续。

但是,如果值小于 1 或大于 10,我在尝试让脚本读回屏幕时遇到问题。每次执行脚本时,无论正确与否,脚本都会退出并转到在“完成”之后回显语句。

如果用户不断输入错误的值,我试图创建一个“无限循环”。

“完成”之后的 echo 语句是我脚本的第二部分,但这不是我遇到问题的部分。

感谢您提供的任何帮助。

脚本:

echo "Please type a number between 1-10."
read insertnum
while [ "$insertnum" -ge 1 -a "$insertnum" -le 10 ]
 do
    if [ "$insertnum" -ge 1 -a "$insertnum" -le 10 ]
     then
# Prompt the user that their answer is acceptable
     echo "Your answer is between 1-10"
     echo
     break
    else
# Prompt the user that their answer is not acceptable
     echo "Your number is not between 1-10."
     echo
     echo "Please type a number between 1-10."
     read insertnum
     echo
fi
done
echo "We will now do a countdown from $insertnum to 0 using a for loop."

答案1

我会这样写:

min=1 max=10
until
  printf "Please type a number between $min-$max: "
  IFS= read -r insertnum
  [ "$insertnum" -ge "$min" ] && [ "$insertnum" -le "$max" ]
do
  echo "Your number is not between $min-$max."
done
echo "Your answer is between $min-$max"
echo
echo "We will now do a countdown from $insertnum to 0 using a for loop."

答案2

这应该有效:

read -p "Please type a number between 1-10: " insertnum
while true; do
    if [ "$insertnum" -ge 1 ] && [ "$insertnum" -le 10 ];then
        # Prompt the user that their answer is acceptable
        echo "Your answer is between 1-10"
        echo
        break
    else
        # Prompt the user that their answer is not acceptable
        echo "Your number is not between 1-10."
        echo
        read -p "Please type a number between 1-10: " insertnum
    fi
done
echo "We will now do a countdown from $insertnum to 0 using a for loop."

我会使用 shell 函数,至少向用户询问数字,因为如果用户输入有效范围之外的数字,这段代码将被执行多次......编程口头禅:不要重复自己。

答案3

while true ; do
  read -p "Please type a number between 1-10: " insertnum
  if [ "${insertnum}" -ge 1 ] && [ "${insertnum}" -le 10 ]
    then
      echo -e "acceptable answer between 1 and 10\n\n\n"
      break
    else
      echo -e "your answer is unacceptable. It has to be be between 1 and 10\n\n\n"
  fi
done
echo "We will now do a countdown from ${insertnum} to 0 using a for loop."

答案4

更短的脚本:

unset a
until  [ "$a" = 1 ]
do     read -p "Please type a number between 1-10: " insertnum
       : $(( a=( insertnum > 0 )&( insertnum < 11 ) ))
       printf 'Your number is %.'"$a"'0sbetween 1-10.\n\n' 'not '
done
echo "We will now do a countdown from $insertnum to 0 using a for loop."

相关内容