##shell编程交互 脚本菜单
shell脚本的交互最常用的方式是使用菜单,通常是echo打印菜单出来。
[root@db ~]# cat echomen.sh
#!/bin/bash
#simple script menu
function diskapace {
clear
df -k
}
function whoseon {
clear
who
}
function menusage {
clear
cat /proc/meninfo
}
function menu {
clear
echo
echo -e "\t\t\t test menu"
echo -e "\t1. Display disk space"
echo -e "\t2. Display logged on users"
echo -e "\t3. Display memory usage"
echo -e "\t0. Exit menu\n\n"
#-en 选项会去掉末尾的换行符,这让菜单看起来更专业一些
echo -en "\t\tEnter option:"
#read 命令读取用户输入
read -n 1 option
}
while [ 1 ]
do
menu
case $option in
0)
break ;;
1)
diskapace ;;
2)
whoseon ;;
3)
menusage ;;
*)
clear
echo "sorry,wrong selection" ;;
esac
echo -en "\n\n\t\thit any to contunue"
read -n 1 line
done
clear
运行:
test menu
1. Display disk space
2. Display logged on users
3. Display memory usage
0. Exit menu
Enter option:
上面的脚本基本上是用echo打印的时间都花在写菜单,为此bash shell提供了一个命令select。
select命令只需要一条命令就可以创建菜单,并获取用户输入,命令格式
select variable in list
do
commands
done
list是由空格组成的文本列表
上面的脚本可以修改为以下这种形式:
#!/bin/bash
#simple script menu
function diskapace {
clear
df -k
}
function whoseon {
clear
who
}
function menusage {
clear
cat /proc/meninfo
}
select option in "Display disk space" "Display logged on users" "Display memory usage" "Exit menu"
do
case $option in
"Exit menu")
break ;;
"Display disk space")
diskapace ;;
"Display logged on users")
whoseon ;;
"Display memory usage")
menusage ;;
*)
clear
echo "sorry,wrong selection" ;;
esac
done
clear
运行:
# ./selectmeun.sh
1) Display disk space 3) Display memory usage
2) Display logged on users 4) Exit menu
#?
可以把菜单选项赋值到变量中,动态的生成菜单项。
例如根据/root目录下的文件修改时间,动态的最新修改的8个文件名菜单项
#!/bin/bash
#test select option men
menu=`ls -t /root/menu | cat | sed -n "1,8p"`
select option in ${menu} "Exit menu"
do
echo ${option}
done
#ls /root/menu
test1 test2 test3 test4 test5 test6 test7 test8 test9
( -t :用文件和目录的更改时间排序)
#ls -t /root/menu
test9 test8 test7 test6 test4 test5 test3 test2 test1
#./dynamicmenu.sh
[root@db ~]# ./men.sh
1) test9 3) test7 5) test4 7) test3 9) Exit menu
2) test8 4) test6 6) test5 8) test2
#?
如果删除一个文件或者增加一个文件,再次执行时菜单项就会变化
删除文件test3 、test5并且创建test10文件后再次执行脚本菜单变化了
1) test10 3) test8 5) test6 7) test2 9) Exit menu
2) test9 4) test7 6) test4 8) test1
#?
注意:在使用select命令中,存储的变量值是菜单中的文本字符串而不是菜单选项中相关联的数字。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有