Linux if else条件语句详解

if 语句


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

if  condition
then
    statement(s)
fi

condition是判断条件,如果 condition 成立(返回“真”),那么 then 后边的语句将会被执行;如果 condition 不成立(返回“假”),那么不会执行任何语句。从本质上讲if是检测命令退出状态。

如果你喜欢,也可以将 then 和 if 写在一行:

if  condition;then
    statement(s)
fi

 

实例1

下面的例子使用 if 语句来比较两个数字的大小

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

 

实例2

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

[root@localhost ~]# vim test.sh 
#!/bin/bash

read a
read b

if (($a>10 && $b<15))
then
 echo "a>10 b<15"
 echo "ha ha"
fi
[root@localhost ~]# ./test.sh 
11
12
a>10 b<15
ha ha

&&就是逻辑“与”运算符,只有当&&两侧的判断条件都为“真”时,整个判断条件才为“真”。

请注意,即使 then 后边有多条语句,也不需要用{ }包围起来,因为有 fi 收尾呢 

 

if else 语句


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

if  condition
then
   statement1
else
   statement2
fi

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

举个例子:

[root@localhost ~]# vim test.sh 
#!/bin/bash

read a
read b

if(($a==$b))
then
   echo "a=b"
else
   echo "a!= b"
fi
  
[root@localhost ~]# ./test.sh 
10
10
a=b
[root@localhost ~]# ./test.sh 
12
10
a!= b

 

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



运行结果1:
19
成年

运行结果2:
100
老年

 

if判断文件,目录是否存在


-d filename 如果 filename为目录,则为真 
-f filename 如果 filename为常规文件,则为真 

目录:

path="/home"
#if [ ! -d ${path} ];then
if [ -d ${path} ];then
    echo dir ${path} exist!
else
    echo dir ${path} not exist!
fi

文件:

file="/home/log.txt"
if [ -f ${file} ];then
    echo file ${file} exist!
else
    echo file ${file} not exist!
fi

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值