shell中if语句详解

if 语句

最简单的用法就是只使用 if 语句,它的语法格式为:

if  condition
then
    statement(s)
fi

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

实例1 test.sh
下面的例子使用 if 语句来比较两个数字的大小:

#!/bin/bash
read a
read b
if (( $a == $b ))
then
    echo "a和b相等"
fi
[root@server1 mnt]# sh test.sh 
1
1
a和b相等

注意: (())是一种数学计算命令,它除了可以进行最基本的加减乘除运算,还可以进行大于、小于、等于等关系运算,以及与、或、非逻辑运算。当 a 和 b 相等时,(( $a == $b ))判断条件成立,进入 if,执行 then 后边的 echo 语句

实例2
在判断条件中也可以使用逻辑运算符:

#!/bin/bash
read age
read iq
if (( $age > 18 && $iq < 60 ))
then
    echo "你都成年了,智商怎么还不及格!"
    echo "来westos学习吧,能迅速提高你的智商。"
fi

测试:

[root@server1 mnt]# sh test.sh 
19
50
你都成年了,智商怎么还不及格!
来westos学习吧,能迅速提高你的智商。

注意:&&就是逻辑“与”运算符,只有当&&两侧的判断条件都为“真”时,整个判断条件才为“真”。
#熟悉其他编程语言的读者请注意,即使 then 后边有多条语句,也不需要用{ }包围起来,因为有 fi 收尾呢

if-else语句

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

测试结果

[root@server1 mnt]# sh test.sh 
2
1
a和b不相等,输入错误

从运行结果可以看出,a 和 b 不相等,判断条件不成立,所以执行了 else 后边的语句

if-elif-else 语句

Shell 支持任意数目的分支,当分支比较多时,可以使用 if elif else 结构,它的格式为:

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

注意,if 和 elif 后边都得跟着 then

整条语句的执行逻辑为:

如果 condition1 成立,那么就执行 if 后边的 statement1;如果 condition1 不成立,那么继续执行 elif,判断 condition2。
如果 condition2 成立,那么就执行 statement2;如果 condition2 不成立,那么继续执行后边的 elif,判断 condition3。
如果 condition3 成立,那么就执行 statement3;如果 condition3 不成立,那么继续执行后边的 elif。
如果所有的 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

测试:

[root@server1 mnt]# sh test.sh 
19
成年

实例二:
输入一个整数,输出该整数对应的星期几的英文表示

#!/bin/bash
printf "Input integer number: "
read num
if ((num==1)); then
    echo "Monday"
elif ((num==2)); then
    echo "Tuesday"
elif ((num==3)); then
    echo "Wednesday"
elif ((num==4)); then
    echo "Thursday"
elif ((num==5)); then
    echo "Friday"
elif ((num==6)); then
    echo "Saturday"
elif ((num==7)); then
    echo "Sunday"
else
    echo "error"

测试:

[root@server1 mnt]# sh test.sh 
Input integer number: 4
Thursday
发布了94 篇原创文章 · 获赞 1 · 访问量 1784

猜你喜欢

转载自blog.csdn.net/qq_36417677/article/details/104394967