我是bash的新手。我想在bash中有一个选择菜单。它有四个选项。这是代码:
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Option 4")
select opt in "${options[@]}"
do
case $opt in
"Option 1")
echo "you chose choice $REPLY which is $opt"
;;
"Option 2")
echo "you chose choice $REPLY which is $opt"
;;
"Option 3")
echo "you chose choice $REPLY which is $opt"
;;
"Exit")
break
;;
*) echo "invalid option $REPLY";;
esac
done
当我执行此代码时,第一次出现带有4个选项的完整菜单,但以后(第二次,第三次和...次)仅出现“请输入您的选择:”。我希望所有4个选项都像第一次一样出现。
作为另一个问题,我希望每次执行程序并重新出现4个选项时,都清除以前的命令和终端内容。我通过在前面加上“清除”来完成此操作:
select opt in "${options[@]}"
但是只有在第一次清除终端内容时才这样。
我该怎么解决这些问题?
答案 0 :(得分:1)
如果用户在未选择任何的情况下按回车,将重新显示菜单。据我所知,以编程方式强制再次绘制菜单的唯一方法是将select
语句包装在另一个循环中,然后重新执行select
语句。您将使用break
退出select
并返回到包装循环的顶部,并使用break 2
退出select
和包装器。
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Option 4")
while :; do
select opt in "${options[@]}"
do
case $opt in
"Option 1")
echo "you chose choice $REPLY which is $opt"
;;
"Find Subdomain")
echo "you chose choice $REPLY which is $opt"
;;
"Option 3")
echo "you chose choice $REPLY which is $opt"
;;
"Option 4")
break 2
;;
*) echo "invalid option $REPLY";;
esac
break
done
done
答案 1 :(得分:1)
您必须添加一个嵌入菜单的新循环,然后为每种情况添加另一个break
,对于选项4,将其编辑为break 2
,如下面的代码所示。我还添加了一个选项,以在选择一个选项后清除屏幕。
#!/bin/bash
PS3='Please enter your choice: '
while true; do
clear
options=("Option 1" "Option 2" "Option 3" "Exit")
select opt in "${options[@]}"
do
case $opt in
"Option 1")
echo "you chose choice $REPLY which is $opt"
break
;;
"Option 2")
echo "you chose choice $REPLY which is $opt"
break
;;
"Option 3")
echo "you chose choice $REPLY which is $opt"
break
;;
"Exit")
break 2
;;
*) echo "invalid option $REPLY";;
esac
done
done
因此使用此代码的情况是:
$ ./select.sh
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 1
you chose choice 1 which is Option 1
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 2
you chose choice 2 which is Option 2
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 3
you chose choice 3 which is Option 3
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 4
$
如果要确保用户可以阅读所选的选项,可以在代码的最后done
之前添加以下行:
read -p "Press [Enter] key to continue..."
这样,用户将看到消息,并且必须按Enter键才能再次显示菜单。
使用这种情况的情况是:
1) Option 1
2) Option 2
3) Option 3
4) Exit
Please enter your choice: 1
you chose choice 1 which is Option 1
Press [Enter] key to continue...