我有以下代码可与用户进行问题对话:
#loop counter
COUNTER=1
# Initial question
echo ""
echo -n "Would you like a cup of tea? (y/n)" # Ask initial question
read answer # Check answer
while [ $COUNTER -le 5 ] # while counter is less than or equal to 5
do
if [ "$answer" != "${answer#[Yy]}" ]; then # if answer is 'y'
echo "" # skip a line for cleanliness
echo "Great, I'll make it now" # Satisfaction
echo ""
break # End the loop
else # if answer is anything other than 'y'
echo "" # skip a line for cleanliness
echo -n "Are you sure? (y/n)" # Ask again
read answer # Check the answer again
let COUNTER=COUNTER+1 # increment COUNTER
fi
done # finish
代码应具有以下作用:
该代码对于点1,2和4正常工作。 在第3点上-代码在结束之前循环到第5个循环。
我似乎无法识别该错误。
编辑:更改为COUNTER = 0,并更改为$ COUNTER -le4。但是,代码在第4次尝试时未实现第4点(即1个初始编号,然后是3个额外的编号,然后是)。
答案 0 :(得分:1)
您可以简单地将计数器限制为小于5,而不是小于或等于。
使用-lt
代替-le
。那就是[ $COUNTER -lt 5]
OR
您可以说小于或等于4,因此可以维持[ $COUNTER -le 4]
答案 1 :(得分:0)
不是2行,而是
echo -n "Are you sure? (y/n)" # Ask again
read answer # Check the answer again
您可以将其缩短为一个:
read -p "Are you sure? (y/n): " answer
但是,我不能完全确定第4点的意思。您能提供一个例子还是更多描述?