Chinaunix首页 | 论坛 | 博客
  • 博客访问: 244009
  • 博文数量: 49
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1334
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-14 08:53
个人简介

勤于思考,默默学习。

文章分类

全部博文(49)

文章存档

2017年(1)

2016年(2)

2015年(1)

2014年(45)

我的朋友

分类: 系统运维

2014-03-16 15:58:19

if-then-else结构能够支持多路的分支(多个elif语句),但如果有多个分支,那么程序就会变得难以阅读。为了解决这个问题,case结构提供了实现多路分支的一种更简洁的方法。
case语法格式(如下):
case 值或变量 in
模式1)
命令列表1
;;
模式2)
命令列表2
;;
......
esac
case语句后是需要进行测试的值或者变量。shell会顺序地把需要测试的值或变量与case结构中指定的模式逐一进行比较,当匹配成功时,则执行该模式相应的命令列表并退出case结构(每个命令列表以两个分号“;;”作为结束)。如果没有发现匹配模式,则会在case后退出case结构。
[root@localhost ~]# vim case.sh 
#!/bin/bash
read -p "please input a number(0-5): " number
case $number in
0)
echo 'The number is 0'
;;
1)
echo 'The number is 1'
;;
2)
echo 'The number is 2'
;;
3)
echo 'The number is 3'
;;
4)
echo 'The number is 4'
;;
5)
echo 'The number is 5'
;;
*)
echo 'this number not in the range'
;;
esac
测试:
[root@localhost ~]# sh case.sh 
please input a number(0-5): 0
The number is 0
[root@localhost ~]# sh case.sh 
please input a number(0-5): 1
The number is 1
[root@localhost ~]# sh case.sh 
please input a number(0-5): 2
The number is 2
[root@localhost ~]# sh case.sh 
please input a number(0-5): 3
The number is 3
[root@localhost ~]# sh case.sh 
please input a number(0-5): 4
The number is 4
[root@localhost ~]# sh case.sh 
please input a number(0-5): 5
The number is 5
[root@localhost ~]# sh case.sh 
please input a number(0-5): 6
this number not in the range
该脚本对number变量的值进行测试,如果与模式匹配的话,则输出相应的信息。
阅读(1761) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~