好的,基本上这就是脚本的样子:
echo -n "Guess my number: "
read guess
while [ $guess != 5 ]; do
echo Your answer is $guess. This is incorrect. Please try again.
echo -n "What is your guess? "
read guess
done
echo "That's correct! The answer was $guess!"
我想改变的是这一行:
while [ $guess != 5 ]; do
对于这样的事情:
while [ $guess != 5 and $guess != 10 ]; do
在Java中我知道“和”是“&&”但这似乎不适用于此。我是否使用while循环以正确的方式进行此操作?
编辑:更新了问题,使其在搜索中更有用..
答案 0 :(得分:39)
有两种正确且便携的方法可以达到你想要的效果
良好的旧shell
语法:
while [ "$guess" != 5 ] && [ "$guess" != 10 ]; do
bash
语法(如您所指定):
while [[ "$guess" != 5 && "$guess" != 10 ]]; do
答案 1 :(得分:26)
bash中的[]
运算符是test
调用的语法糖,man test
中对此进行了记录。 “或”由中缀-o
表示,但您需要“和”:
while [ $guess != 5 -a $guess != 10 ]; do
答案 2 :(得分:1)
可移植且可靠的方法是使用case
语句。如果你不习惯它,可能需要一些看起来只是围绕语法。
while true; do
case $guess in 5 | 10) break ;; esac
echo Your answer is $guess. This is incorrect. Please try again.
echo -n "What is your guess? "
read guess # not $guess
done
我使用while true
但您实际上可以直接使用case
语句。但是,阅读和维护会变得毛茸茸。
while case $guess in 5 | 10) false;; *) true;; esac; do ...