测试与分支(case与select结构)

来源:互联网 发布:centos网卡速率命令 编辑:程序博客网 时间:2024/05/25 20:01

case

在代码块中控制程序分支.


case (in) / esac

case "$variable" in    $condition1 )        command...    ;;    $condition2 )        command...    ;;    .    .esac
  • 每句测试行,都以右小括号 ) 来结尾.
  • 每个条件判断语句块都以一对分号结尾 ;;.
  • case块以esac(case的反向拼写)结尾.

例: 使用命令替换来产生case变量.

#!/bin/bash# case-cmd.sh: 使用命令替换来产生"case"变量.case $( arch ) in  # "arch"返回机器体系的类型,等价于'uname -m'.    i386 )        echo "80386-based machiine"    ;;    i486 )        echo "80486-based machiine"    ;;    i586 )        echo "Pentium-based machiine"    ;;    i686 )        echo "Pentium2+-based machiine"    ;;    x86_64 )        echo "Lenovo G50-80-liudezhi linux"    ;;    * )        echo "Other type of machine"    ;;esacexit 0

select

select结构是建立菜单的另一种工具,这种结构是从ksh中引入的.


select variable [in list]do    command...    breakdone

*提示用户输入选择的内容(比如放在变量列表中). 注意: select命令使用 PS3 提示符, 默认为( #? ), 可以修改.


例:使用select来创建菜单.

#!/bin/bash# select.shPS3='Choose your favorite vegetable: '                 #设置提示符字串. select vegetable in "beans" "carrots" "potatoes" "onions" "rutabagas"do    echo "Your favorite veggie is $vegetable."    echo "Yuck!"    break                                               # 若不加break将不能退出select结构.        doneexit 0

如果忽略了 in list 列表, 那么select命令将会使用传递到脚本的命令行参数( $@ ), 或者是函数参数(当select是在函数中时).


例: 使用函数中的select结构来创建菜单.

#!/bin/bash# select_func.shPS3='Choose your favorite vegetable: 'choice_of(){    select vegetable    do        echo        echo "Your favorite veggie is $vegetable."        echo "Yuck!"        echo        break    done}choice_of bean carrots potatoes onions      #choice_of "bean" "carrots" "potatoes" "onions" #          $1     $2      $3      $4# 传递给choice_of()的参数.exit 0
原创粉丝点击