shell脚本学习(十)——if语句

1 if语句的基本格式

格式

if  condition
then
	statement(s)
fi	

还有第二种格式,就是当condition和then在一行时,中间用;隔开,这里的;必须加否则会出现错误

if condition;then
	statement
fi

示例一:

#!/bin/bash
if date					
then
        echo "it works"	
fi						

在这里插入图片描述
示例二:

#!/bin/bash
if datefffff				
then
	echo "it works"		
fi						
echo "we are outside of if"

在这里插入图片描述
示例三:

#!/bin/bash
testing=student
if grep $testing /etc/passwd
then
	echo The bash files for user $testing are:
	ls -a /home/$testing/.b*
fi

在这里插入图片描述

2 if-else语句

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

格式

if condition
then
	statement1
else
	statement2
fi

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

示例一:

#!/bin/bash
read num1
read num2
if (($num1 == $num2))
then
	echo $num1$num2相等
else
	echo $num1$num2不相等

fi

在这里插入图片描述
示例二:

#!/bin/bash
read num1
read num2

if ((num1>=18 && num2<=60))	#同时满足多个条件时用&&相连
then
	echo $num1
	echo $num2
else
	echo "Sorry."
fi

在这里插入图片描述

3 if-elif-else语句

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

格式

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

整条语句的执行逻辑为:
如果condition1成立,那么就执行if后边的statement1;如果condition1 不成立,那么继续执行elif,判断condition2;
如果condition2成立,那么就执行statement2;如果condition2 不成立,那么继续执行elif,判断condition3;
如果condition3成立,那么就执行是statement3;如果condition13不成立,那么继续执行elif。
如果所有的if和elif判断都不成立,就进入最后的else,执行statementn。

注意: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

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值