【发布时间】:2013-10-26 22:33:59
【问题描述】:
我有一个使用 case 语句完成主菜单的脚本。脚本运行,欢迎屏幕信息回显到屏幕,用户按回车键清除欢迎屏幕内容(空的读取语句),要求用户输入与菜单项对应的数字(读取 menuNum)。它按原样工作正常,但我想稍微扩展功能并允许用户在运行脚本时通过使用参数跳过欢迎屏幕并直接进入菜单项。
例如,如果我的菜单是:1) 文件操作 2) 用户信息 3) 进程,那么我希望用户在控制台中键入“scriptfile.sh 文件”以直接进入文件菜单。这会以某种方式分配 menuNum=1。
我不知道这是否可以通过输入重定向来实现,或者是否真的可以。任何帮助或提示将不胜感激。谢谢。
基本上,这是我的脚本:
#!/bin/bash
#DEFINE ARGUMENTS
if [[ "$1" = "man" ]]; then man ./manpage.txt; exit; fi #argument "man" opens man page, closes main script
if [ "$1" = "debug" ]
then clear
echo -e "This area provides debug information:\n"
echo -e "There's a lot here, but it's not related to my question."
echo -e "\nPress [Enter] to continue."
read
fi
if [[ "$1" = "file" ]]; then bash tsharonfp.sh < 1; exit; fi #go straight to file menu
if [[ "$1" = "user" ]]; then bash tsharonfp.sh < 2; exit; fi #go straight to user menu
if [[ "$1" = "info" ]]; then bash tsharonfp.sh < 3; exit; fi #go straight to info menu
if [[ "$1" = "fun" ]]; then bash tsharonfp.sh < 4; exit; fi #go straight to fun menu
if [[ "$1" = "process" ]]; then bash tsharonfp.sh < 5; exit; fi #go straight to proc menu
#/DEFINE ARGUMENTS
clear
echo -e "My script title, contact info, and other stuff gets printed to screen here."
read #hitting enter clears welcome screen stuff
clear
while : #opens while1 loop
do #while1 loop
echo -e "Main Menu\n"
echo -e "[1] File Menu\n[2] User Menu\n[3] Info Menu\n[4] Fun Menu\n[5] Process Menu\n[88] Exit\n[99] Shutdown"
echo -ne "\nEnter Choice: "
read menuNum
case $menuNum in #open mainmenu case
1) #File;; #statement isn't commented, of course, but you get the idea
2) #user;;
3) #info;;
4) #fun;;
5) #proc;;
88) exit;;
99) shutdown -h;;
*) echo "invalid input";;
esac #closes mainmenu case
done #closes while1 loop
【问题讨论】:
-
显示你拥有的脚本。
-
我看不出 tsharonfp.sh 在做什么的问题?如果 tsharonfp.sh 必须接受 {1,...,5,88,99} 中的参数,您应该以这种方式传递它
if [[ "$1" = "file" ]]; then bash tsharonfp.sh 1; exit; fi而不是tsharonfp.sh <1; -
1.您不需要在
[[内引用变量,只需在[内引用(即使值具有嵌入的空格)。您只需要在文本嵌入空格时引用它们。 2.你可以考虑then exec bash tsharonfp.sh "$1" fi。使用exec意味着不需要exit(除非exec失败)。 3. 最好将你的脚本模块化。
标签: bash shell menu arguments case