Shell脚本编程之创建文本菜单
2016/06/10
创建交互式shell脚本最常用的方法是使用菜单。提供各种选项可以帮助脚本用户了解脚本能做什么,不能做什么;通常菜单脚本会清空显示区域,然后显示可用的选项列表。用户可以按下与每个选项关联的字母或数字来选择选项
Shell脚本菜单的核心是case命令,case命令会根据用户在菜单上的选择来执行特定命令
1. 使用典型的case语句创建文本菜单:
2. 使用select命令创建菜单
select 命令的格式如下:
list参数是构成菜单的空格分割的文本选项列表。select命令会在列表中将每个选项作为一个编好号的选项显示,然后为选项显示一个特殊的由
PS3环境变量定义的提示符。
创建交互式shell脚本最常用的方法是使用菜单。提供各种选项可以帮助脚本用户了解脚本能做什么,不能做什么;通常菜单脚本会清空显示区域,然后显示可用的选项列表。用户可以按下与每个选项关联的字母或数字来选择选项
Shell脚本菜单的核心是case命令,case命令会根据用户在菜单上的选择来执行特定命令
1. 使用典型的case语句创建文本菜单:
#!/bin/bash
#simple script menu
function diskspace {
clear
df -k
}
function whoseon {
clear
who
}
function memusage {
clear
cat /proc/meminfo
}
function menu {
clear
echo
echo -e "\t\tSys Admin Menu"
echo -e "\t1. Display disk space"
echo -e "\t2. Display logged on users"
echo -e "\t3. Display memory usage"
echo -e "\t0. Exit program\n\n"
echo -en "\tEnter option: "
read -n 1 option
}
while [ 1 ]
do
menu
case $option in
0)
break ;;
1)
diskspace ;;
2)
whoseon ;;
3)
memusage ;;
*)
clear
echo "Sorry.wrong selection" ;;
esac
echo -en "\n\n\t\t\tHit any key to continue: "
read -n 1 line
done
clear
#simple script menu
function diskspace {
clear
df -k
}
function whoseon {
clear
who
}
function memusage {
clear
cat /proc/meminfo
}
function menu {
clear
echo
echo -e "\t\tSys Admin Menu"
echo -e "\t1. Display disk space"
echo -e "\t2. Display logged on users"
echo -e "\t3. Display memory usage"
echo -e "\t0. Exit program\n\n"
echo -en "\tEnter option: "
read -n 1 option
}
while [ 1 ]
do
menu
case $option in
0)
break ;;
1)
diskspace ;;
2)
whoseon ;;
3)
memusage ;;
*)
clear
echo "Sorry.wrong selection" ;;
esac
echo -en "\n\n\t\t\tHit any key to continue: "
read -n 1 line
done
clear
2. 使用select命令创建菜单
select 命令的格式如下:
select variable in list
do
commands
done
do
commands
done
list参数是构成菜单的空格分割的文本选项列表。select命令会在列表中将每个选项作为一个编好号的选项显示,然后为选项显示一个特殊的由
PS3环境变量定义的提示符。
#!/bin/bash
#simple script menu
function diskspace {
clear
df -k
}
function whoseon {
clear
who
}
function memusage {
clear
cat /proc/meminfo
}
PS3="Enter option: "
select option in "Display disk space" "Display logged on users" "Display memory usage" "Exit program"
do
case $option in
"Exit program")
break ;;
"Display disk space")
diskspace ;;
"Display logged on users")
whoseon ;;
"Display memory usage")
memusage ;;
*)
clear
echo "Sorry.wrong selection"
esac
done
clear
#simple script menu
function diskspace {
clear
df -k
}
function whoseon {
clear
who
}
function memusage {
clear
cat /proc/meminfo
}
PS3="Enter option: "
select option in "Display disk space" "Display logged on users" "Display memory usage" "Exit program"
do
case $option in
"Exit program")
break ;;
"Display disk space")
diskspace ;;
"Display logged on users")
whoseon ;;
"Display memory usage")
memusage ;;
*)
clear
echo "Sorry.wrong selection"
esac
done
clear
【声明】欢迎转载,但请保留文章原始出处:http://blog.csdn.net/yelangjueqi/article/details/51636682