我想创建一个while循环,要求用户输入yes或no,如果用户输入其他任何内容,它将一直循环直到用户输入yes或no
echo "Do you wish to save these settings?"
read response
while [ "$response" != "yes" ] | [ "$response != "no" ]
do
echo "Please enter yes or no only"
echo "Do you wish to save these settings?"
read response
done
当我尝试输入“是”时,它仍然继续循环,但是当我输入“否”时,它退出循环
答案 0 :(得分:1)
在外壳中,|
(或管道)运算符用于使用右侧的命令过滤左侧的命令输出。
例如,下面的shell行:
seq 1 3 | tac
...将导致左侧命令产生的行...
1
2
3
...由左侧的命令过滤(它将以相反的顺序发出行)。输出将是:
3
2
1
您正在寻找对两个命令的退出状态执行布尔运算的运算符。由于您一直希望只要响应既不是yes
也不是no
,就可以继续循环,因此,求和运算符(&&
)就是您想要的:
echo "Do you wish to save these settings?"
read response
while [ "$response" != "yes" ] && [ "$response" != "no" ]
do
echo "Please enter yes or no only"
echo "Do you wish to save these settings?"
read response
done
如果在运行脚本的任何地方bash
外壳程序始终可用,则可以通过使用[[ ... ]]
而不是[ ... ]
来进一步改进。除了潜在的性能优势外,使用[[
的另一个优势是放宽了对严格引用的要求:
echo "Do you wish to save these settings?"
read response
while [[ $response != yes ]] && [[ $response != no ]]
do
echo "Please enter yes or no only"
echo "Do you wish to save these settings?"
read response
done
进一步的改进来自以下知识:[[
支持&&
连接两个布尔表达式:
echo "Do you wish to save these settings?"
read response
while [[ $response != yes && $response != no ]]
do
echo "Please enter yes or no only"
echo "Do you wish to save these settings?"
read response
done
答案 1 :(得分:0)
只需while true
,直到满意为止
while true
do
echo "Do you wish to save these settings?"
read response
if [[ "$response" = "yes" ]] || [[ "$response" = "no" ]]
then
break
fi
echo "Please enter yes or no only"
done