zoukankan      html  css  js  c++  java
  • 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系列教程

  • 相关阅读:
    Git常用命令
    更新CentOS内核
    VMware虚拟机安装Ubuntu系统步骤详解
    Ubuntu安装遇到的问题
    IOT OS and OTA
    gcc c asm,C程序内嵌汇编
    makefile and make tips
    RTEMS目录梳理Sparc
    关于FreeRTOS的信号量、队列
    FreeRTOS任务源码分析以及程序堆栈与任务堆栈的关系
  • 原文地址:https://www.cnblogs.com/waitig/p/5868343.html
Copyright © 2011-2022 走看看