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

勤于思考,默默学习。

文章分类

全部博文(49)

文章存档

2017年(1)

2016年(2)

2015年(1)

2014年(45)

我的朋友

分类: 系统运维

2014-03-16 15:55:41

在shell脚本中支持的控制结构有:
if-then-else、case、for、while和until等。(下面将逐一介绍)
if-then-else是一种基于条件测试结果的流程控制结构。如果测试结果为真,则执行控制结构中相应的命令列表,否则将进行另外一个条件测试或者退出该控制结构。
语法格式(如下):
if 条件1
then 命令列表1
elif 条件2
then 命令列表2
else 命令列表3
fi
他的执行逻辑是这样的:当条件1成立时,则执行命令列表1并退出if-then-else控制结构;如果条件2成立,则执行命令列表2并退出if-then-else控制结构;否则执行命令列表3并退出if-then-else控制结构。在同一个if-then-else结构中只能有一条if语句和一条else语句,elif可以有多条。其中if语句是必须的,elif和else语句是可选的。
例1(if-then-fi):
[root@localhost ~]# ll file 
-rw-r--r-- 1 root root 0  8月  2 20:33 file
[root@localhost ~]# vim if-then-fi.sh
#!/bin/bash
filename=file
if [ -r $filename ]
then
echo $filename' is readable !'
fi
[root@localhost ~]# sh if-then-fi.sh 
file is readable !
shell首先判断文件file是否可读,如果是则输出is readable !的提示信息;否则不进行任何动作。
例2(if-then-else-fi):
[root@localhost ~]# vim if-then-else-fi.sh 
#!/bin/bash
read -p "please input a number: " number
if [ $number -eq 100 ]
then
echo 'The number is equal 100 !'
else
echo 'The number is not equal 100!!!'
fi
[root@localhost ~]# sh if-then-else-fi.sh 
please input a number: 100
The number is equal 100 !
[root@localhost ~]# sh if-then-else-fi.sh 
please input a number: 110
The number is not equal 100!!!
[root@localhost ~]#
定义一个变量number,如果输入的数字等于100,则显示“The number is equal 100 !”,如果输入的数字不等于100则显示“The number is not equal 100!!!”。
例3:(if-then-elif-else-fi)
[root@localhost ~]# vim if-then-elif-else-fi.sh
#!/bin/bash
read -p "please input a number: " number
if [ $number -lt 10 ]
then
echo "$number <10 !"
elif [ $number -ge 10 -a $number -lt 20 ]
then
echo "10 =< $number <20 !"
elif [ $number -ge 20 -a $number -lt 30 ]
then
echo "20 =< $number <30 !"
else
echo "30 <= $number"
fi
[root@localhost ~]# sh if-then-elif-else-fi.sh 
please input a number: 5
5 <10 !
[root@localhost ~]# sh if-then-elif-else-fi.sh 
please input a number: 15
10 =< 15 <20 !
[root@localhost ~]# sh if-then-elif-else-fi.sh 
please input a number: 25
20 =< 25 <30 !
[root@localhost ~]# sh if-then-elif-else-fi.sh 
please input a number: 35
30 <= 35
[root@localhost ~]#
shell脚本首先判断$number变量是否小于10,如果是则输出$numer<10;否则,判断$number变量是否大于等于10且小于20。如果是,则输出10<=$number<20;否则判断$number变量是否大于等于20且小于30。如果是,则输出20<=$nunber<30;否则,输出30<=$number。
阅读(1860) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~