shell编程----if语句


1. if语句

if语句形式:

If condition
then
statement(s)
fi
If condition;then
	statement(s)
fi

请注意condition后面的分号;,当if和then位于同一行时候,这个分号是必须的,否则会有语法错误。

#!/bin/bash

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

结果:
student❌1000:1000:Student User:/home/student:/bin/bash
The bash files for user student are:
/home/student/.bash_logout /home/student/.bashrc
/home/student/.bash_profile

#!/bin/bash

read a
read b
if (($a==$b))
then
	echo "a和b相等"
fi

结果:
[root@localhost 2-12]# sh 04.sh
3
3
a和b相等

2. if-else语句

格式:

if condition
then
	statement1
else
	statement2
fi

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

read a
read b
if (($a==$b))
then
	echo "a和b相等"
else
	echo "a和b不相等"

fi

结果:
2
4
a和b不相等

3. if-elif-else语句

格式:

if conditionn1
then
	statement1
elif condition2
then
	statement2
elif condition3
then
	statement3
....
else
	ststement
fi

注意:if和elif后面都得跟着then

#!/bin/bash
read age
if (($age<=18));then
	echo "未成年"
elif (($age>18 && $age<=60));then
	echo "成年"
else
	echo "老年"
fi

结果:
33
成年

发布了106 篇原创文章 · 获赞 1 · 访问量 2355

猜你喜欢

转载自blog.csdn.net/weixin_43384009/article/details/104315193