if
是 Shell 脚本中最常用的条件判断语句,用于根据条件执行不同的代码块。结合 test
(或 [ ]
)、文件检查、字符串比较、数值判断等,可以实现复杂的逻辑控制。
1. if
基础语法
1.1 基本格式
if [ 条件1 ]; then
# 条件1成立时执行的代码
elif [ 条件2 ]; then
# 条件2成立时执行的代码
else
# 所有条件均不成立时执行的代码
fi
[ ]
是test
命令的简写,括号内两侧必须有空格。then
和fi
是if
语句的开始和结束标志。elif
(else if
的缩写)和else
是可选的。
1.2 if
的三种写法
(1) 单行写法
if [ 条件 ]; then 命令; fi
if [ -f "/etc/passwd" ]; then echo "文件存在"; fi
(2) 多行写法
if [ 条件 ]
then
命令1
命令2
fi
(3) 使用 [[ ]]
if [[ -f "/etc/passwd" && -r "/etc/passwd" ]]; then
echo "条件成立"
fi
2. 运维实战案例
案例 1:Ping测试主机状态
版本一:
[root@lichu ~]# vim ping_host_check1.sh
#!/bin/bash
Target_Host="www.lichu228.top"
if ping -c2 -W2 "$Target_Host" &>/dev/null; then
echo "[SUCCESS] Host $Target_Host is reachable."
else
echo "[FAILED] Host $Target_Host is unreachable."
fi
版本二:
[root@lichu ~]# vim ping_host_check2.sh
#!/bin/bash
read -p "Input HOST or IP: " Target_Host
if ping -c2 -W2 "$Target_Host" &>/dev/null; then
echo "[SUCCESS] Host $Target_Host is reachable."
else
echo "[FAILED] Host $Target_Host is unreachable."
fi
版本三:
[root@lichu ~]# vim ping_host_check3.sh
#!/bin/bash
Target_Host=$1
if [ $# -eq 0 ];then
echo "使用方法: $(basename $0) HOST"
exit 1
fi
if ping -c2 -W2 "$Target_Host" &>/dev/null; then
echo "[SUCCESS] Host $Target_Host is reachable."
else
echo "[FAILED] Host $Target_Host is unreachable."
fi
补充知识:
[root@lichu ~]# basename /etc/sysconfig/network-scripts/ifcfg-ens33
ifcfg-ens33
[root@lichu ~]# dirname /etc/sysconfig/network-scripts/ifcfg-ens33
/etc/sysconfig/network-scripts
案例 2:检查服务是否运行
[root@lichu ~]# vim check_service_status.sh
#!/bin/bash
service="nginx"
if systemctl is-active --quiet "$service"; then
echo "$service 正在运行"
else
echo "$service 未运行,尝试启动..."
systemctl start "$service"
fi
案例 3:根据发行版安装软件
[root@lichu ~]# vim install_nginx.sh
#!/bin/bash
# 安装Nginx软件
# 检查root权限
if [ "$(id -u)" -ne 0 ]; then
echo "请使用root用户或sudo运行此脚本"
exit 1
fi
# 检测系统类型
if [ -f /etc/redhat-release ]; then
echo "检测到CentOS系统,使用yum安装Nginx"
# 安装EPEL仓库+Nginx
yum install -y epel-release
yum install -y nginx
# 启动Nginx并设置开机自启
systemctl start nginx
systemctl enable nginx
elif [[ -f /etc/lsb-release || -f /etc/debian_version ]]; then
echo "检测到Ubuntu/Debian系统,使用apt安装Nginx"
# 更新软件包列表
apt-get update
# 安装Nginx
apt-get install -y nginx
# 启动Nginx并设置开机自启
systemctl start nginx
systemctl enable nginx
else
echo "不支持的Linux发行版"
exit 1
fi
# 检查Nginx是否安装成功
if which nginx &>/dev/null; then
echo -e "\nNginx安装成功!"
echo -e "Nginx版本信息:$(nginx -v 2>&1 | awk -F"/" '{print $2}')"
echo -e "Nginx服务状态:"
systemctl status nginx | grep -E "Active:|Loaded:"
echo -e "可以通过浏览器访问服务器IP地址来验证Nginx是否正常运行"
else
echo "Nginx安装失败,请检查错误信息"
exit 1
fi
1. CentOS测试
分别使用普通用户和root测试
Nginx安装成功!
Nginx版本信息:1.20.1
Nginx服务状态:
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2025-08-13 11:30:51 CST; 9min ago
可以通过浏览器访问服务器IP地址来验证Nginx是否正常运行
2. Ubuntu测试
lichu@yangge:~$ sudo ./install_inginx.sh
Nginx安装成功!
Nginx版本信息:1.24.0 (Ubuntu)
Nginx服务状态:
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
Active: active (running) since Wed 2025-08-13 03:32:10 UTC; 9min ago
可以通过浏览器访问服务器IP地址来验证Nginx是否正常运行
案例 4:磁盘空间监控
[root@lichu ~]# yum -y install mailx
[root@lichu ~]# vim monitor_disk_space.sh
#!/bin/bash
threshold=20 # 阈值 20%
usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$usage" -ge "$threshold" ]; then
echo "[$(date +%F-%T)]警告: /分区使用率 ${usage}%,请清理磁盘!" | mail -s "磁盘告警" root
fi
[root@lichu ~]# ./monitor_disk_space.sh
[root@lichu ~]# mail
Heirloom Mail version 12.5 7/5/10. Type ? for help.
"/var/spool/mail/root": 1 message 1 new
>N 1 root Wed Aug 13 14:22 18/645 "磁盘告警"
扩展:可以使用cron例如每天2:00执行脚本
案例 5:备份文件
[root@lichu ~]# backup_files.sh
#!/bin/bash
backup_file="/backup/data_$(date +%F).tar.gz"
source_dir="/etc"
[ ! -e /backup ] && mkdir /backup
if [ ! -f "$backup_file" ]; then
tar -czf "$backup_file" "$source_dir" &>/dev/null
echo "备份完成: $backup_file"
else
echo "备份文件已存在,跳过"
fi
[root@lichu ~]# ./backup_files.sh
备份完成: /backup/data_2025-08-13.tar.gz
[root@lichu ~]# ./backup_files.sh
备份文件已存在,跳过
[root@lichu ~]# date -s "2025-08-14"
Thu Aug 14 00:00:00 CST 2025
[root@lichu ~]# ./backup_files.sh
备份完成: /backup/data_2025-08-14.tar.gz
案例 6:检查端口是否监听
[root@lichu ~]# check_port_listening.sh
#!/bin/bash
port=80
if netstat -tnlp | grep -q ":$port "; then
echo "端口 $port 正在监听"
else
echo "端口 $port 未监听"
fi
案例 7:用户输入验证
[root@lichu ~]# check_user_input.sh
#!/bin/bash
read -p "请输入数字 (1-10): " num
if [[ "$num" =~ ^[0-9]+$ ]]; then
if [ "$num" -ge 1 -a "$num" -le 10 ]; then
echo "输入有效: $num"
else
echo "数字不在 1-10 范围内"
fi
else
echo "请输入数字!"
fi
案例 8:成绩等级判断
[root@lichu ~]# vim grade_check.sh
#!/bin/bash
# 提示用户输入成绩
read -p "请输入成绩(0-100):" score
# 检查输入是否为数字
if ! [[ "$score" =~ ^[0-9]+$ ]]; then
echo "错误:请输入有效的数字!"
exit 1
fi
# 判断成绩等级
if (( score >= 90 && score <= 100 )); then
echo "成绩等级:A(优秀)"
elif (( score >= 80 && score < 90 )); then
echo "成绩等级:B(良好)"
elif (( score >= 70 && score < 80 )); then
echo "成绩等级:C(中等)"
elif (( score >= 60 && score < 70 )); then
echo "成绩等级:D(及格)"
elif (( score >= 0 && score < 60 )); then
echo "成绩等级:F(不及格)"
else
echo "错误:成绩必须在 0-100 之间!"
fi