SHELL脚本编程循环篇-select循环
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.select循环的语法格式
[root@node101.yinzhengjie.org.cn ~]# help select select: select NAME [in WORDS ... ;] do COMMANDS; done Select words from a list and execute commands. The WORDS are expanded, generating a list of words. The set of expanded words is printed on the standard error, each preceded by a number. If `in WORDS' is not present, `in "$@"' is assumed. The PS3 prompt is then displayed and a line read from the standard input. If the line consists of the number corresponding to one of the displayed words, then NAME is set to that word. If the line is empty, WORDS and the prompt are redisplayed. If EOF is read, the command completes. Any other value read causes NAME to be set to null. The line read is saved in the variable REPLY. COMMANDS are executed after each selection until a break command is executed. Exit Status: Returns the status of the last command executed. [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
select variable in list do 循环体命令 done
温馨提示: select 循环主要用于创建菜单,按数字顺序排列的菜单项将显示在标准错误上,并显示 PS3 提示符,等待用户输入 用户输入菜单列表中的某个数字,执行相应的命令 用户输入被保存在内置变量 REPLY 中 select 是个无限循环,因此要记住用 break 命令退出循环,或用 exit 命令终止脚本。也可以按 ctrl+c 退出循环 select 经常和 case 联合使用 与 for 循环类似,可以省略 in list,此时使用位置参量
二.案例实战(自定义菜单)
[root@node101.yinzhengjie.org.cn ~]# cat shell/select_menu.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/menu.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** #使用PS3来自定义select对应的提示符 PS3="Please input a number>>>: " select MENU in 鲍鱼 海参 佛跳墙 龙虾 帝王蟹 燕窝 quit;do #注意,这里的"$REPLY"变量就是上面select的列表中对应的值 case $REPLY in 1|2) echo "The price 100" ;; 3|5) echo "The price 150" ;; 4|6) echo "The price 80" ;; 7) echo "bye..." break ;; *) echo "Choose false" ;; esac done [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/select_menu.sh 1) 鲍鱼 2) 海参 3) 佛跳墙 4) 龙虾 5) 帝王蟹 6) 燕窝 7) quit Please input a number>>>: 1 The price 100 Please input a number>>>: 2 The price 100 Please input a number>>>: 3 The price 150 Please input a number>>>: 4 The price 80 Please input a number>>>: 5 The price 150 Please input a number>>>: 6 The price 80 Please input a number>>>: 7 bye... [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#