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

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"
    ;;
esac

exit 0

select

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


select variable [in list]
do
    command...
    break
done

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


例:使用select来创建菜单.

#!/bin/bash
# select.sh

PS3='Choose your favorite vegetable: '                 #设置提示符字串. 

select vegetable in "beans" "carrots" "potatoes" "onions" "rutabagas"
do
    echo "Your favorite veggie is $vegetable."
    echo "Yuck!"
    break                                               # 若不加break将不能退出select结构.        
done

exit 0

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


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

#!/bin/bash
# select_func.sh

PS3='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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值