shell脚本基础知识梳理<八>:流程控制select
select variable in list
do # 循环开始的标志
commands # 循环变量每取一次值,循环体就执行一遍
done # 循环结束的标志
专注于为中小企业提供成都网站建设、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业十堰免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000+企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
select 循环主要用于创建菜单,按数字顺序排列的菜单项将显示在标准错误上,等待用户输入
菜单项的间隔符由环境变量 IFS 决定
用于引导用户输入的提示信息存放在环境变量 PS3 中
用户直接输入回车将重新显示菜单
与 for 循环类似,省略 in list 时等价于 in “$*”
用户输入菜单列表中的某个数字,执行相应的命令
用户的输入被保存在内置变量 REPLY 中。
实例 1
#!/bin/bash
#
#IFS 是系统分隔符变量;未指定输入参数变量,系统默认把脚本后跟输入的参数存放REPLY变量里
clear
PS3="What is your preferred OS?"
IFS='|'
OS="Linux|Gnu Hurd|FreeBSD|Mac OS X"
select s in $OS
do
case $REPLY in
1|2|3|4) echo "You selected $s" ;;
*) exit ;;
esac
done
执行结果
1) Linux
2) Gnu Hurd
3) FreeBSD
4) Mac OS X
What is your preferred OS?1
You selected Linux
What is your preferred OS?4
You selected Mac OS X
What is your preferred OS?e
[root@localhost shell]#
实例 2
#!/bin/bash
#
#PS3 用户自定义的提示信息
clear
PS3="What is your preferred scripting language?"select s in bash perl python ruby quit
do
case $s in
bash|perl|python|ruby)
echo "You selected $s"
;;
quit) exit ;;
*) echo "You selected error,retry " ;;
esac
执行结果
1) bash
2) perl
3) python
4) ruby
5) quit
What is your preferred scripting language?1
You selected bash
What is your preferred scripting language?2
You selected perl
What is your preferred scripting language?5
[root@localhost shell]#
实例 3
#!/bin/bash
#
#命令包查看脚本
PS3="Select a program you want to execute: "
TOPLIST="wget telnet htop atop nettop iftop ftop"
clear
select prog in $TOPLIST quit
do
[[ $prog == quit ]] && exit
rpm -q $prog > /dev/null && echo "$prog installed" || echo "$prog is not installed"done
执行结果
1) wget 3) htop 5) nettop 7) ftop
2) telnet 4) atop 6) iftop 8) quit
Select a program you want to execute: 1
wget installed
Select a program you want to execute: 8
[root@localhost shell]#
文章标题:shell脚本基础知识梳理<八>:流程控制select
标题来源:http://azwzsj.com/article/jcjjih.html