我刚刚开始学习bash脚本并尝试练习循环和if语句,所以请耐心等待。 当我运行脚本时,总是得到打印信息
You entered an invalid option.
无论选择什么选项,都意味着loopControl
的值没有改变。
loopControl="z"
echo "Choose one of the following options."
while [ "$loopControl" != "Q" ] && [ "$loopControl" != "q" ] do
echo "A"
echo "B"
echo "C"
echo "Q";
read $loopControl
if [ "$loopControl" == "A" ] || [ "$loopControl" == "a" ]
then echo "option A works"
elif [ "$loopControl" == "B" ] || [ "$loopControl" == "b" ]
then echo "option B works"
elif [ "$loopControl" == "C" ] || [ "$loopControl" == "c" ]
then echo "option c works"
else
echo "You entered an invalid option."
fi
done
答案 0 :(得分:1)
替换:
read $loopControl
使用:
read loopControl
然后,您的代码即可使用。
完整的脚本是:
$ cat script.sh
#!bin/bash
loopControl="z"
echo "Choose one of the following options."
while [ "$loopControl" != "Q" ] && [ "$loopControl" != "q" ]
do
echo "A"
echo "B"
echo "C"
echo "Q"
read -r loopControl
if [ "$loopControl" == "A" ] || [ "$loopControl" == "a" ]
then
echo "option A works"
elif [ "$loopControl" == "B" ] || [ "$loopControl" == "b" ]
then
echo "option B works"
elif [ "$loopControl" == "C" ] || [ "$loopControl" == "c" ]
then
echo "option c works"
else
echo "You entered an invalid option."
fi
done
在操作中,它的工作方式如下:
$ bash script.sh
Choose one of the following options.
A
B
C
Q
a
option A works
A
B
C
Q
B
option B works
A
B
C
Q
c
option c works
A
B
C
Q
q
You entered an invalid option.
select
在bash
中获取菜单的更常规方法是使用select
:
$ cat script2.sh
#!bin/bash
loopControl="z"
echo "Choose one of the following options."
select loopControl in A B C Q
do
case "$loopControl" in
A) echo "option A works" ;;
B) echo "option B works" ;;
C) echo "option c works" ;;
Q) exit ;;
*) echo "You entered an invalid option." ;;
esac
done
其工作原理略有不同:输入选项编号。但是,最终结果非常相似:
$ bash script2.sh
Choose one of the following options.
1) A
2) B
3) C
4) Q
#? 1
option A works
#? 3
option c works
#? 5
You entered an invalid option.
#? 4
$