shell中的if语句

1. if语句的基本格式

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

注意:这里的then和if可以位于一行,位于一行时condition后要加分号:

if condition;then
	statement
fi

例1:

#!/bin/bash
if date					#如果能够正常执行date命令
then
        echo "it works"	#就输出it works
fi						#date命令的执行结果也会被输出

在这里插入图片描述

例2:

#!/bin/bash
if datfff    			#如果能够正常执行datefff命令
then
	echo "it works"		#就输出it works
fi						#如果不能执行datefff,就跳出if语句,执行下面的内容
echo "we are outside if the if statement"

在这里插入图片描述

例3:

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

在这里插入图片描述

例4:

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

在这里插入图片描述

例5:

#!/bin/bash
read num1
read num2
if (( $num1 >18 && $num2 < 60 ))
then
		echo $num1
		echo $num2
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
	statementn
fi

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

整条语句的执行逻辑为:
如果condition1成立,那么就执行if后面的statement1;如果condition1不成立,就继续执行elif,判断condition2;
如果condition2成立,那么就执行if后面的statement2;如果condition2不成立,就继续执行elif,判断condition3;

以此类推…

如果所有的if和elif判断都不成立,就进入最后的else,执行statementn。

例:

#!/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<=25));then
	echo "成年"
elif (($age>=26 && $age<=40));then
	echo "青年"
elif (($age>=41 && $age<=60));then
	echo "中年"
else
	echo "老年"
fi

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章