![在 Bash 中创建嵌套菜单](https://linux22.com/image/851488/%E5%9C%A8%20Bash%20%E4%B8%AD%E5%88%9B%E5%BB%BA%E5%B5%8C%E5%A5%97%E8%8F%9C%E5%8D%95.png)
我想在选择选项“a”时在选项“a”下创建更多菜单。如果用户输入选项“a”,我希望它有几个菜单供您选择,其中一个选项是返回“主菜单”。这是我遇到的两个问题。我尝试对此处的菜单执行与下面相同的格式,并将其放在“A”代码块下,但没有成功。
#!/bin/bash
ok=0;
while ((ok==0))
do
echo "Main Menu:"
echo -e "\t(a) More Menu Options "
echo -e "\t(b) Exit"
echo -n "Please enter your choice:"
read choice
case $choice in
"a"|"A")
ok=1
;;
"b"|"B")
exit
;;
*)
echo "invalid answer, please try again"
;;
esac
done
答案1
为什么不把相同的循环放在里面呢?
#!/bin/bash
while :
do
echo "Main Menu:"
echo -e "\t(a) More Menu Options "
echo -e "\t(b) Exit"
echo -n "Please enter your choice:"
read choice
case $choice in
"a"|"A")
while :
do
echo "Secondary menu"
echo -e "\t(c) Print this menu again"
echo -e "\t(d) Return to main menu"
echo -n "Please enter your choice:"
read choice1
case $choice1 in
"c"|"C")
;;
"d"|"D")
break
;;
*)
echo "invalid answer, please try again"
;;
esac
done
;;
"b"|"B")
exit
;;
*)
echo "invalid answer, please try again"
;;
esac
done
还有select
创建菜单的命令:
select i in ant bee cat
do
echo $i
break
done
让我们运行它:
$ select i in ant bee cat; do echo $i; break; done
1) ant
2) bee
3) cat
#? 2
bee
答案2
尝试这个:
#!/bin/bash
submanual(){
while :
do
echo "sub Menu:"
echo -e "\t(x) Options 1"
echo -e "\t(y) Options 1"
echo -e "\t(e) Back"
echo -n "Please enter your choice:"
read c
case $c in
"x"|"X")
# Options 1 and its commands
;;
"y"|"Y")
# Options 2 and its commands
;;
"e"|"E")
break
;;
*)
echo "invalid answer, please try again"
;;
esac
done
}
while :
do
echo "Main Menu:"
echo -e "\t(a) More Menu Options "
echo -e "\t(b) Exit"
echo -n "Please enter your choice:"
read choice
case $choice in
"a"|"A")
submanual
;;
"b"|"B")
exit
;;
*)
echo "invalid answer, please try again"
;;
esac
done