我对 Unix 很陌生,我需要有关此案例陈述的帮助。我想做的是让用户用case语句选择一个变量,然后让系统读取用户选择的结果。这是我的脚本结构(作为示例):
CHOOSEfruit () {
clear
echo "Choose fruit you need to buy (a.Apple b.Banana c.Pear d.Pineapple)"
read FRUIT
case $FRUIT in
a|A)
echo "Apple"
;;
b|B)
echo "Banana"
;;
c|C)
echo "Pear"
;;
d|D)
echo "Pineapple"
;;
esac
clear
echo "The fruit you need to buy is $FRUIT"
echo ""
read -p "Press [Enter] key to go back to main menu"
clear
}
如果我选择“a”,我希望我的脚本输出:“您需要购买的水果是苹果”
答案1
通过循环可以更好地解决这个问题select
:
PS3='Please select fruit from the menu: '
select fruit in 'No fruit please' Apple Banana Pear Pineapple; do
case $REPLY in
1)
# User wants no fruit
unset fruit
break
;;
[2-5])
# All ok, exit loop
break
;;
*)
# Invalid choice
echo 'Try again' >&2
esac
done
if [ -n "$fruit" ]; then
printf 'The fruit you need is %s\n' "$fruit"
else
echo 'You selected no fruit!'
fi
该select
循环在交互式菜单中向用户呈现选项列表。向用户提供从菜单中选择项目的提示是 中的字符串$PS3
。
在循环体中select
, in 的值$fruit
将是用户选择的实际文本字符串,而$REPLY
将是用户在提示符下键入的任何内容。
请注意,无需case ... esac
在循环中使用语句。您可以在这里使用任何代码。例如,您可能会觉得使用更舒服if ... then ... elif ... else ... fi
:
if [ "$REPLY" = 1 ]; then
unset fruit
break
elif [[ $REPLY == [2-5] ]]; then
break
else
echo 'Try again' >&2
fi
与任何其他无限循环一样,select
使用 退出循环。break
运行该代码三次:
$ bash script
1) No fruit please
2) Apple
3) Banana
4) Pear
5) Pineapple
Please select fruit from the menu: 1
You selected no fruit!
$ bash script
1) No fruit please
2) Apple
3) Banana
4) Pear
5) Pineapple
Please select fruit from the menu: 2
The fruit you need is Apple
$ bash script
1) No fruit please
2) Apple
3) Banana
4) Pear
5) Pineapple
Please select fruit from the menu: 6
Try again
Please select fruit from the menu: 3
The fruit you need is Banana
答案2
你几乎做对了。只需像这样编辑您的案例陈述:
case $FRUIT in
a|A)
FRUIT="Apple"
;;
b|B)
FRUIT="Banana"
;;
c|C)
FRUIT="Pear"
;;
d|D)
FRUIT="Pineapple"
;;
esac