【运维进阶】if 条件语句的知识与实践
if 条件语句的知识与实践
if 条件语句
Shell 脚本中的 if
条件语句用于根据条件判断结果执行不同的命令块,基本结构如下:
if [ 条件表达式 ]; then# 条件为真时执行的命令
elif [ 另一个条件表达式 ]; then# 前一条件为假,当前条件为真时执行的命令
else# 所有条件都为假时执行的命令
fi
核心特点:
- 条件表达式需用
[ ]
包裹,且内部前后需有空格 - 用
then
标识条件成立后执行的代码块 - 可通过
elif
增加多个判断分支 - 用
else
处理所有条件都不满足的情况 - 以
fi
作为语句结束标记
常见判断类型:
- 文件状态判断(是否存在、是否为目录等)
- 字符串比较(是否相等、是否为空等)
- 数值比较(大于、小于、等于等)
- 命令执行结果判断(返回值是否为 0)
通过 if
语句,脚本可以根据不同情况动态执行相应操作,实现程序的分支逻辑。
if 条件语句的语法
1. 单分支结构
第一种语法:
if <条件表达式>then 指令
fi
第二种语法:
if <条件表达式>;then指令
fi
上文的“<条件表达式>”部分可以是test、口、[[]]、(())等条件表达式,甚至可以直接使用命令作为条件表达式。每个if条件语句都以if开头,并带有then,最后以fi结尾。
第二种语法中的分号相当于命令换行,上面的两种语法含义是相同的,日常主要用第二种。
if单分支语句执行流程逻辑图如下:
条件语句还可以嵌套**(即if条件语句里面还有if条件语句)**,注意每个if条件语句中都要有一个与之对应的fi(if反过来写),每个if和它下面最近的fi成对搭配,语法示例如下:
if <条件表达式>;thenif <条件表达式>;then指令fi
fi
**提示:**通常在书写Shell条件语句时,要让成对的条件语句关键字的缩进相对应,以便于阅读浏览。
前文曾讲解过的文件条件表达式:
[ ! -d /tmp/lth ] && mkdir /tmp/lth
# 等价于下面的if条件语句:
if [ ! -d /tmp/lth ];thenmkdir /tmp/lth
fi
2. 双分支结构
if条件语句的双分支结构主体则为:“如果…,那么…,否则…”。
if条件语句的双分支结构语法为:
if <条件表达式>;then指令集1
else指令集2
fi
if 双分支语句执行流程逻辑图如下:
前文的文件测试条件表达式
[ -d /tmp/lth ] && echo /tmp/lth is exist || mkdir /tmp/lth
就相当于下面的双分支的if条件语句:
if [ -d /tmp/lth ];thenecho /tmp/lth is exist
elsemkdir /tmp/lth
fi
3. 多分支结构
if条件语句多分支结构的主体为:“如果…,那么…,否则如果…,那么,否则如果…,那么…,否则…”。
if条件语句多分支语法为:
if <条件表达式1>;then指令1
elif <条件表达式2>;then指令2
else指令3
fi
多个elif
if <条件表达式1>;then指令
elif <条件表达式2>;then指令
elif <条件表达式3>;then指令
else指令
fi
提示:
- 注意多分支elif的写法,每个elif都要带有then。
- 最后结尾的else后面没有then。
if多分支语句执行流程对应的逻辑图如下:
if 条件语句多种条件表达式语法
Shell 中 if
条件语句的 <条件表达式>
主要有以下 5 种形式,核心作用是判断条件真假以决定是否执行后续指令,具体归纳如下(含代码示例):
1. test条件表达式
if test 表达式; then指令
fi
**特点:**基础判断形式,通过 test
命令进行条件检查。
2. []条件表达式
if [ 字符串 或 算术表达式 ]; then指令
fi
特点:test
命令的简化写法,需注意括号内各元素间必须有空格,支持字符串和算术判断。
3. [[]]条件表达式
if [[ 字符串 或 算术表达式 ]]; then指令
fi
**特点:**功能更强大,支持模式匹配和 &&
||
等逻辑运算符直接使用,语法更灵活。
4. (())条件表达式
if (( 算术表达式 )); then指令
fi
**特点:**专为算术运算设计,可直接使用 +
-
*
/
等运算符,无需转义。
5. 命令表达式
if 命令; then指令
fi
**特点:**以命令执行结果为判断依据,命令返回状态码为 0 则条件为真,否则为假。
这些表达式虽语法形式不同,但核心功能一致,实际使用时可根据个人习惯和具体场景选择合适的形式。
if 条件语句实践
示例1:检测sshd服务是否运行,如果未运行则启动sshd服务。
[root@controller bin 19:36:31]# cat if1_sshd
#!/bin/bash
systemctl is-active sshd &>/dev/null
if [ $? -ne 0 ];thenecho "sshd is not running, I'll start sshd."systemctl start sshd
fi# 执行
[root@controller bin 19:39:21]# bash if1_sshd
sshd is not running, I'll start sshd.
[root@controller bin 19:39:23]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since 四 2025-08-21 19:39:23 CST; 7s agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 2884 (sshd)CGroup: /system.slice/sshd.service└─2884 /usr/sbin/sshd -D8月 21 19:39:23 controller.xiexin.cloud systemd[1]: Starting OpenSSH server daemon...
8月 21 19:39:23 controller.xiexin.cloud sshd[2884]: Server listening on 0.0.0.0 port 22.
8月 21 19:39:23 controller.xiexin.cloud sshd[2884]: Server listening on :: port 22.
8月 21 19:39:23 controller.xiexin.cloud systemd[1]: Started OpenSSH server daemon.
示例2:检测sshd服务是否运行,如果未运行则启动sshd服务;如果运行,输出 “Running”。
[root@controller bin 19:39:31]# cat if2_sshd
#!/bin/bash
systemctl is-active sshd &>/dev/null
if [ $? -ne 0 ];thenecho "sshd is not running."echo -n "Starting sshd ... ..."systemctl start sshd && echo DONE
elseecho "sshd is running"
fi# 执行
[root@controller bin 19:41:26]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since 四 2025-08-21 19:39:23 CST; 2min 9s agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 2884 (sshd)CGroup: /system.slice/sshd.service└─2884 /usr/sbin/sshd -D8月 21 19:39:23 controller.xiexin.cloud systemd[1]: Starting OpenSSH server daemon...
8月 21 19:39:23 controller.xiexin.cloud sshd[2884]: Server listening on 0.0.0.0 port 22.
8月 21 19:39:23 controller.xiexin.cloud sshd[2884]: Server listening on :: port 22.
8月 21 19:39:23 controller.xiexin.cloud systemd[1]: Started OpenSSH server daemon.
[root@controller bin 19:41:33]# bash if2_sshd
sshd is running
[root@controller bin 19:41:46]# systemctl stop sshd
[root@controller bin 19:42:09]# bash if2_sshd
sshd is not running.
Starting sshd ... ...DONE
示例3:通过传参控制sshd服务。
[root@controller bin 19:44:07]# cat if3_sshd
#!/bin/bash
if [ "$1" == "start" ];thensystemctl start sshd
elif [ "$1" == "stop" ];thensystemctl stop sshd
elif [ "$1" == "status" ];thensystemctl status sshd
elif [ "$1" == "restart" ];thensystemctl restart sshd
elseecho "Usage: $0 start|stop|status|restart "
fi# 执行
[root@controller bin 19:44:59]# chmod +x if3_sshd
[root@controller bin 19:45:08]# bash if3_sshd
Usage: if3_sshd start|stop|status|restart
“status” ];then
systemctl status sshd
elif [ “$1” == “restart” ];then
systemctl restart sshd
else
echo "Usage: $0 start|stop|status|restart "
fi
执行
[root@controller bin 19:44:59]# chmod +x if3_sshd
[root@controller bin 19:45:08]# bash if3_sshd
Usage: if3_sshd start|stop|status|restart