shell中的if语句

shell中的if语句

1.if语句

if语句的格式

shell中的if语句的语法格式为:

if condition		#如果满足condition条件
then
	statement(s)	#就执行statement(可以有多个)
fi

或者if 和 else 位于一行:

if condition;then
	statement(s)
fi

注意:当if和else位于一行时,必须在condition后面加上分好,否则会出现语法问题

if语句的规则

  if语句后面跟的是命令 ,会执行命令,判断命令的退出状态,如果命令的退出状态是0,就执行then语句;否则不执行then里面的语句。

例子1:

#!/bin/bash
if date					#正常执行date命令,使得退出状态为0
then
        echo "it works"	
fi						#date命令的执行结果也会被输出

在这里插入图片描述
例子2:

#!/bin/bash
if dateeeee				#不正常执行命令,使得退出状态非0
then
	echo "it works"		
fi						
echo "we are outside of the if statement" #判断if语句外的语句能否被执行

在这里插入图片描述
例子3:

#!/bin/bash
testing=student
if grep $testing /etc/passwd  #若/etc/passwd文件里与student用户相关的语句存在(退出状态为0)
then
	echo The bash files for user $testing are:
	ls -a /home/$testing/.b*  ##就列出所有student家目录下以.b开头的文件
fi

在这里插入图片描述

2.if else语句

如果语句有两个分支,就可以使用if-else语句
格式:

if condition
then
	statement1
else
	statement2
fi

如果condition成立,那么then后面的statement1将会被执行;
否则,执行else后面的statement2语句

例子:

#!/bin/bash
read a
read b
if (($a == $b))
then
	echo "a和b相等"
else
	echo "a和b不相等"
fi

在这里插入图片描述

3.if elif else语句

shell支持任意数目的分支,当分支比较多时,可以使用if elif else 结构

格式:

if condition1
then
	statement1
elif condition2
then
	statement2
elif condition3
then
	statement3
......
else
	statement
fi

其逻辑为:
如果condition1成立,那么就执行if后面的statement1;
如果condition1不成立,就继续执行elif,判断condition2;
以此类推
如果所有的if和elif判断都不成立,就进入最后的else,执行statement

注意:if和eilf后面都要跟then

例子 :

#!/bin/bash
read age
if (($age<=2));then
echo 婴儿
elif (($age>=3 && $age<=8));then
echo 幼儿
elif (($age>=9 && $age<=17));then
echo 少年
elif (($age>=18 && $age<=40));then
echo 青年
elif (($age>=41 && $age<=60));then
echo 中年
else
echo 老年
fi

在这里插入图片描述

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值