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


    本文是Linux Shell系列教程的第(十四)篇,更多Linux Shell教程请看:Linux Shell系列教程

    在上一篇文章:Linux Shell系列教程之(十三)Shell分支语句case … esac教程 的最后,我们简单的介绍了一下使用case…esac来建立菜单的方法,其实shell中还有另外一种更专业的建立菜单的语句:select语句。

    Shell select教程

    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系列教程

  • 相关阅读:
    sublime开启vim模式
    git命令行界面
    搬进Github
    【POJ 2886】Who Gets the Most Candies?
    【UVA 1451】Average
    【CodeForces 625A】Guest From the Past
    【ZOJ 3480】Duck Typing
    【POJ 3320】Jessica's Reading Problemc(尺取法)
    【HDU 1445】Ride to School
    【HDU 5578】Friendship of Frog
  • 原文地址:https://www.cnblogs.com/waitig/p/5868343.html
Copyright © 2020-2023  润新知