(转)Linux Shell系列教程之(十四) Shell Select教程

本文属于《 Linux Shell 系列教程》文章系列,该系列共包括以下 18 部分:
  1. Linux Shell系列教程之(一)Shell简介
  2. Linux Shell系列教程之(二)第一个Shell脚本
  3. Linux Shell系列教程之(三)Shell变量
  4. Linux Shell系列教程之(四)Shell注释
  5. Linux Shell系列教程之(五)Shell字符串
  6. Linux Shell系列教程之(六)Shell数组
  7. Linux Shell系列教程之(七)Shell输出
  8. Linux Shell系列教程之(八)Shell printf命令详解
  9. Linux Shell系列教程之(九)Shell判断 if else 用法
  10. Linux Shell系列教程之(十)Shell for循环
  11. Linux Shell系列教程之(十一)Shell while循环
  12. Linux Shell系列教程之(十二)Shell until循环
  13. Linux Shell系列教程之(十三)Shell分支语句case … esac教程
  14. Linux Shell系列教程之(十四) Shell Select教程
  15. Linux Shell系列教程之(十五) Shell函数简介
  16. Linux Shell系列教程之(十六) Shell输入输出重定向
  17. Linux Shell系列教程之(十七) Shell文件包含
  18. 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语句的语法如下所示:

select name   [in   list ] 
do 
    statements that can use  $name... 
done

说明:select首先会产生list列表中的菜单选项,然后执行下方do…done之间的语句。用户选择的菜单项会保存在$name变量中。

另外:select命令使用PS3提示符,默认为(#?);

在Select使用中,可以搭配PS3=’string’来设置提示字符串。

二、Shell Select语句的例子

还是老样子,通过示例来学习Shell select的用法:

#!/bin/bash  
#Author:linuxdaxue.com
#Date:2016-05-30
#Desc:Shell select 练习
PS3='Please choose your number: ' # 设置提示符字串.  
echo
select number in "one" "two" "three" "four" "five"  
do  
echo  
echo "Your choose is $number."    
echo  
break  
done 
exit 0

说明:上面例子给用户呈现了一个菜单让用户选择,然后将用户选择的菜单项显示出来。

这是一个最基本的例子,主要为大家展示了select的基础用法。当然,你也可以将break去掉,让程序一直循环下去。

下面是去掉break后输出:

$./select.sh
1) one
2) two
3) three
4) four
5) five
Please choose your number: 1

Your choose is one.

Please choose your number: 2

Your choose is two.

Please choose your number: 3

Your choose is three.

Please choose your number: 4

Your choose is four.

Please choose your number: 5

Your choose is five.

然后我们将例子稍稍修改下,加入case…esac语句:

#!/bin/bash  
#Author:linuxdaxue.com
#Date:2016-05-30
#Desc:Shell select case 练习
PS3='Please choose your number: ' # 设置提示符字串.  
echo
select number in "one" "two" "three" "four" "five"  
do
case $number in
one )
echo Hello one!
;;
two )
echo Hello two!
;;
* )
echo  
echo "Your choose is $number."    
echo
;;
esac
#break  
done 
exit 0

这样的话,case会对用户的每一个选项进行处理,然后执行相应的语句。输出如下:

$./select2.sh
1) one
2) two
3) three
4) four
5) five
Please choose your number: 1
Hello one!
Please choose your number: 2
Hello two!
Please choose your number: 3

Your choose is three.

Please choose your number: 4

Your choose is four.

将这些语句进行修改拓展,就可以写出非常复杂的脚本。怎么样,是不是非常强大呢,赶快试试吧!

更多Linux Shell教程请看:Linux Shell系列教程

猜你喜欢

转载自www.cnblogs.com/liujiacai/p/9591492.html