温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

shell脚本基础知识梳理<八>:流程控制 select

发布时间:2020-08-06 09:01:27 来源:网络 阅读:219 作者:wx5cb5dcd871bbc 栏目:系统运维

select variable in list
do # 循环开始的标志
commands # 循环变量每取一次值,循环体就执行一遍
done # 循环结束的标志

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]#

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI