Select语句的强大菜单能力
时间:2005-11-28 来源:xktop
经常在linux下运行一些程序吧,是否很羡慕一些程序有很不错的菜单结构呢,现在我们也可以利用bash的select语句实现shell脚本的菜单功能。select的语法和for除了关键字不同外,其他是一样的,其语法为:
select opt [in list]
do
code
done
下面是我学习时编写的一个小例子,麻雀虽小,结构还是很完整的,脚本s.sh如下:
#!/bin/bash
PS3="which is your hobby? Please select :"
OPTIONS="computer:music:math:art"
IFS=:
select selected in $OPTIONS;do
case $selected in
computer) echo "you select 1";;
music) echo "you select 2 ";;
math) echo "you select math";;
art) echo "you select art";;
*) echo "error";exit 1;;
esac
done
说明,系统变量PS3中存储的是select菜单的提示信息,系统变量IFS中存储的首字符是列表分割符,很明显我自定义的列表OPTION的分割符是:。运行脚本s.sh,可得到如下结果:
xk@linux:~/work> sh s.sh
1) computer
2) music
3) math
4) art
which is your hobby? Please select:1
you select 1
which is your hobby? Please select:2
you select 2
which is your hobby? Please select:3
you select math
which is your hobby? Please select:4
you select art
which is your hobby? Please select:5
error
xk@linux:~/work>
是不是很不错呢,大家都试试吧。