本文属于《 Linux Shell 系列教程》文章系列,该系列共包括以下 18 部分:
- Linux Shell系列教程之(一)Shell简介
- Linux Shell系列教程之(二)第一个Shell脚本
- Linux Shell系列教程之(三)Shell变量
- Linux Shell系列教程之(四)Shell注释
- Linux Shell系列教程之(五)Shell字符串
- Linux Shell系列教程之(六)Shell数组
- Linux Shell系列教程之(七)Shell输出
- Linux Shell系列教程之(八)Shell printf命令详解
- Linux Shell系列教程之(九)Shell判断 if else 用法
- Linux Shell系列教程之(十)Shell for循环
- Linux Shell系列教程之(十一)Shell while循环
- Linux Shell系列教程之(十二)Shell until循环
- Linux Shell系列教程之(十三)Shell分支语句case … esac教程
- Linux Shell系列教程之(十四) Shell Select教程
- Linux Shell系列教程之(十五) Shell函数简介
- Linux Shell系列教程之(十六) Shell输入输出重定向
- Linux Shell系列教程之(十七) Shell文件包含
- Linux Shell 系列教程目录
系列详情请看:《Linux Shell 系列教程》:
Linux Shell 系列教程,欢迎加入Linux技术交流群:479935456
原文:https://www.linuxdaxue.com/linux-shell-select-command.html
Select 搭配 case来使用,可以完成很多复杂的菜单控制选项。
select和其他流控制不一样,在C这类编程语言中并没有类似的语句,今天就为大家介绍下Shell Select语句的用法。
一、Shell Select语句语法
Shell中Select语句的语法如下所示:
1select name [in list ] 2do 3 statements that can use $name... 4done
说明:select首先会产生list列表中的菜单选项,然后执行下方do…done之间的语句。用户选择的菜单项会保存在$name变量中。
另外:select命令使用PS3提示符,默认为(#?);
在Select使用中,可以搭配PS3=’string’来设置提示字符串。
二、Shell Select语句的例子
还是老样子,通过示例来学习Shell select的用法:
1#!/bin/bash 2#Author:linuxdaxue.com 3#Date:2016-05-30 4#Desc:Shell select 练习 5PS3='Please choose your number: ' # 设置提示符字串. 6echo 7select number in "one" "two" "three" "four" "five" 8do 9echo 10echo "Your choose is $number." 11echo 12break 13done 14exit 0
说明:上面例子给用户呈现了一个菜单让用户选择,然后将用户选择的菜单项显示出来。
这是一个最基本的例子,主要为大家展示了select的基础用法。当然,你也可以将break去掉,让程序一直循环下去。
下面是去掉break后输出:
1$./select.sh 21) one 32) two 43) three 54) four 65) five 7Please choose your number: 1 8 9Your choose is one. 10 11Please choose your number: 2 12 13Your choose is two. 14 15Please choose your number: 3 16 17Your choose is three. 18 19Please choose your number: 4 20 21Your choose is four. 22 23Please choose your number: 5 24 25Your choose is five.
然后我们将例子稍稍修改下,加入case…esac语句:
1#!/bin/bash 2#Author:linuxdaxue.com 3#Date:2016-05-30 4#Desc:Shell select case 练习 5PS3='Please choose your number: ' # 设置提示符字串. 6echo 7select number in "one" "two" "three" "four" "five" 8do 9case $number in 10one ) 11echo Hello one! 12;; 13two ) 14echo Hello two! 15;; 16* ) 17echo 18echo "Your choose is $number." 19echo 20;; 21esac 22#break 23done 24exit 0
这样的话,case会对用户的每一个选项进行处理,然后执行相应的语句。输出如下:
1$./select2.sh 21) one 32) two 43) three 54) four 65) five 7Please choose your number: 1 8Hello one! 9Please choose your number: 2 10Hello two! 11Please choose your number: 3 12 13Your choose is three. 14 15Please choose your number: 4 16 17Your choose is four.
将这些语句进行修改拓展,就可以写出非常复杂的脚本。怎么样,是不是非常强大呢,赶快试试吧!
更多Linux Shell教程请看:Linux Shell系列教程