一、IF 语句
1.1 语法
1.1.1 单分支语法
# 单分支if条件判断;thencommandfiif条件判断thencommandfi条件判断&&command1.1.2 双分支语法
# 单分支if条件判断;thencommand1elsecommand2fi条件判断&&command1||command21.1.3 多分支语法
# 单分支if条件1判断;thencommand1elif条件2判断;thencommand2elsecommand3fi1.2 实践
示例1:单分支
需求:如果sshd服务正常运行,则提示服务正在运行。
开发脚本if_sshd_1.sh ,内容如下:
[root@centos7 bin13:53:41]# vim if_ssh_1.sh#!/bin/bashstatus="$(systemctl is-active sshd)"if["$status"=="active"];thenechosshd is running.fi# 或者#!/bin/bashsystemctl is-active sshd&>/dev/nullif(($?==0));thenechosshd is running.fi运行结果:
[root@centos7 bin13:46:42]# systemctl start sshd[root@centos7 bin13:46:46]# bash if_sshd_1.shsshd is running.示例2:双分支
需求:
- 如果sshd服务正常运行,则提示服务正在运行
- 提示服务未运行,并启动服务,启动后提示服务正常运行。
开发脚本if_sshd_2.sh ,内容如下:
[root@centos7 bin13:43:41]# vim if_ssh_2.sh#!/bin/bashstatus="$(systemctl is-active sshd)"if["$status"=="active"];thenechosshd is running.elsesystemctl start sshd&&echo"Start sshd success."fi运行结果:
[root@centos7 bin13:44:04]# systemctl stop sshd[root@centos7 bin13:44:57]# bash if_sshd_2.shStart sshd success.[root@centos7 bin13:45:01]# bash if_sshd_2.shsshd is running.示例3:多分支
需求:开发if_sshd_3.ctl脚本。
- 脚本使用方法:“Usage:$0 start|stop|status|restart|reload”
- 如果参数数量个数不是1个,则输出脚本使用方法。
- 如果$1是start,则执行’systemctl start sshd’
- 如果$1是stop,则执行’systemctl stop sshd’
- 如果$1是status,则执行’systemctl status sshd’
- 如果$1是restart,则执行’systemctl restart sshd’
- 如果$1是reload,则执行’systemctl reload sshd’
如果$1是其他子命令,则输出脚本使用方法。
[root@centos7 ~14:20:32]# vim if_sshd_3.ctl#!/bin/bashservice_name=sshdif(($#!=1));thenecho"Usage:$0start|stop|status|restart|reload"exitfiif["$1"=="start"];thensystemctl start${service_name}elif["$1"=="stop"];thensystemctl stop${service_name}elif["$1"=="status"];thensystemctl status${service_name}elif["$1"=="restart"];thensystemctl restart${service_name}elif["$1"=="reload"];thensystemctl reload${service_name}elseecho"Usage:$0start|stop|status|restart|reload"fi运行结果:
[root@centos7 ~14:16:15]# chmod +x if_sshd_3.ctl# 缺乏参数[root@centos7 ~14:22:41]# if_sshd_3.ctlUsage: /root/bin/if_sshd_3.ctl start|stop|status|restart|reload# 只能传递1个参数[root@centos7 bin14:24:32]# if_sshd_3.ctl stopUsage:/root/bin/if_sshd_3.sh start|stop|status|restart|reload# 传递正常参数[root@centos7 bin14:53:46]# if_sshd_3.ctl status● sshd.service - OpenSSH server daemon Loaded: loaded(/usr/lib/systemd/system/sshd.service;enabled;vendor preset: enabled)Active: active(running)since Mon2026-04-1314:53:46 CST;1s ago Docs: man:sshd(8)man:sshd_config(5)Main PID:11882(sshd)CGroup: /system.slice/sshd.service └─11882 /usr/sbin/sshd-DApr1314:53:46 centos7.jqz.cloud systemd[1]: Starting OpenSSH server daemon... Apr1314:53:46 centos7.jqz.cloud sshd[11882]: Server listening on0.0.0.0 port22. Apr1314:53:46 centos7.jqz.cloud sshd[11882]: Server listening on :: port22. Apr1314:53:46 centos7.jqz.cloud systemd[1]: Started OpenSSH server daemon.# 传递不存在的参数[root@centos7 bin14:55:30]# if_sshd_3.sh addvssvdUsage:/root/bin/if_sshd_3.sh start|stop|status|restart|reload优化后脚本-不带注释
#!/bin/bashservice_name=sshdaction="$1"if(($#!=1));thenecho"Usage:$0start|stop|status|restart|reload$2"exitfiif["$1"=="start"-o"$1"=="stop"-o"$1"=="status"-o"$1"=="restart"-o"$1"=="reload"];thensystemctl$action${service_name}elseecho"Usage:$0start|stop|status|restart|reload"fi优化后脚本-带注释
#!/bin/bash# 功能:一键管理 sshd 服务的启动/停止/重启/状态查看# 用法:./脚本名 start|stop|status|restart|reload# 定义要管理的服务名称为 sshd(远程登录服务)service_name=sshd# 接收用户输入的第一个参数(动作:start/stop/restart等)action="$1"# ==============================================# 判断参数个数:如果参数数量不等于1,就提示用法并退出# $# 表示脚本接收的参数个数# ==============================================if(($#!=1));then# 输出正确用法提示echo"Usage:$0start|stop|status|restart|reload$2"# 退出脚本exitfi# ==============================================# 判断用户输入的参数是否合法# 支持:start | stop | status | restart | reload# ==============================================if["$1"=="start"-o"$1"=="stop"-o"$1"=="status"-o"$1"=="restart"-o"$1"=="reload"];then# 如果参数合法,执行 systemctl 命令管理服务systemctl$action${service_name}else# 如果参数不合法,提示正确用法echo"Usage:$0start|stop|status|restart|reload"fi二、FOR语句
2.1 语法
2.1.1 shell自带语法
for变量名in清单docommanddone2.2.2 C语言格式语法
for((num=1;num<=10;num++))doecho$numdone# 执行效果如下123456789102.2 实践
2.2.2 示例1:计算1+2+…+9+10的和
[root@centos7 bin15:18:22]# cat for1.sh#!/bin/bashsum=0fornumin{1..10}dosum=$[sum+num]doneecho"1+2+..+9+10=$sum"[root@centos7 bin15:18:18]# bash for1.sh1+2+..+9+10=552.2.3 示例2:批量重命名文件
具体需求:将某个目录下文件名中字符串snap替换为pic
模拟:
[root@centos7 bin15:18:26]# mkdir Pictures[root@centos7 bin15:37:04]# touch Pictures/snap-{1..10}.jpg[root@centos7 bin15:50:21]# cat for_2_rename.sh#!/bin/bashforfileinPictures/snap*dofile_old_name=$filefile_new_name=${file_old_name/snap/pic}mv${file_old_name}${file_new_name}done执行效果如下:
[root@centos7 bin15:49:57]# bash for_2_rename.sh[root@centos7 bin15:50:04]#[root@centos7 bin15:50:04]# ls Pictures/pic-10.jpg pic-2.jpg pic-4.jpg pic-6.jpg pic-8.jpg pic-1.jpg pic-3.jpg pic-5.jpg pic-7.jpg pic-9.jpg2.2.4 示例3:批量创建用户
公司新入职一批员工,需要为这些员工创建账号。
员工姓名清单保存在staff.txt中,每行一个。
为每个员工创建一个初始密码,初始密码是8位随机值,要求登录后必须修改密码。
创建的结果要保存到users_info.conf中,格式为username: password。
准备员工姓名清单:
[root@centos7 bin15:52:47]# vim staff.txt[root@centos7 bin16:15:34]# cat staff.txtjack tom zhangsan laowang脚本内容如下:
[root@centos7 bin16:28:08]# cat for_3_users.sh#!/bin/bashstaff_name_file=staff.txtstaff_info_file=users_info.confif[-a${staff_name_file}-a-r${staff_name_file}];thenforstaffin$(cat${staff_name_file})douseradd$staffpassword=$(date+%N|md5sum|head-c10)echo$password|passwd--stdin$staff&>/dev/nullecho"$staff:$password">>${staff_info_file}doneelseecho"${staff_name_file}is not exist."fi执行效果如下:
[root@centos7 bin16:25:55]# bash for_3_users.sh[root@centos7 bin16:28:03]# cat users_info.confjack: 141a940129 tom: b1b23719df zhangsan: 70745fb6dd laowang: 594d0504bd2.2.5 生成随机值常见方法:
- 利用时间生成纳秒级别值:date +%N
[root@centos7 bin16:04:25]# date +%N456812617- mktemp命令创建一个临时目录,目录名是随机值。
[root@centos7 bin16:05:14]# echo $(mktemp)/tmp/tmp.ncZkKK9TYD- 利用环境变量RANDOM生成0~32767随机值。
2.3 总结:$() $[] ${}
- $() :命令替换
- $[]:数值计算
- ${}:变量替换
三、while/until
条件满足或者不满足,一直运行。
3.1 语法
3.1.1 while
条件满足,一直运行。
while条件判断docommanddone3.1.2 until
条件不满足,一直运行。满足条件,则终止运行。
3.2 实践
3.2.1 示例1:挣1个小目标
while_1_target.sh 脚本内容如下:
#!/bin/bashtarget=100000000money=100while((money<target))doecho-n"I'm working hard ... "sleep1money=$[money+10000000]echo$moneydone# 执行结果[root@centos7 bin17:14:46]# bash while_1_target.shI'm working hard ... 10000100 I'm working hard...20000100I'm working hard ... 30000100 I'm working hard...40000100I'm working hard ... 50000100 I'm working hard...60000100I'm working hard ... 70000100 I'm working hard...80000100I'm working hard ... 90000100 I'm working hard...100000100[root@centos7 bin17:15:01]#3.2.2 示例 2:监控 sshd 服务
开发脚本monitor_sshd.sh 实时监控sshd服务,实现以下功能:
- 如果sshd服务没有运行,则报告sshd服务状态到/tmp/sshd_status.log日志;同时启动sshd服务,启动的结果也写入/tmp/sshd_status.log日志。
- 如果sshd服务正常运行,则报告sshd服务状态,并写入/tmp/sshd_status.log日志
- 每隔3秒执行一次监控。
monitor_sshd.sh 脚本内容如下:
[root@centos7 bin17:22:37]# cat monitor_sshd.sh#!/bin/bashlog_file=/tmp/sshd_status.logwhiletruedostatus=$(systemctl is-active sshd)if["$status"=="active"];thenecho"$(date): sshd status is running."|tee-a${log_file}elseecho"$(date): sshd status is not running."|tee-a${log_file}systemctl start sshd&>/dev/null&&\echo"$(date): Start sshd success."|tee-a${log_file}||\echo"$(date): Start sshd fail."|tee-a${log_file}fisleep3done执行效果如下:
[root@centos7 bin17:22:21]# bash monitor_sshd.shMon Apr1317:22:26 CST2026: sshd status is running. Mon Apr1317:22:29 CST2026: sshd status is running. Mon Apr1317:22:32 CST2026: sshd status is running. Mon Apr1317:22:35 CST2026: sshd status is running. ^C新开终端关闭sshd服务,监控日志变化
[root@centos7 bin17:22:58]# systemctl stop sshd[root@centos7 bin17:23:17]# bash monitor_sshd.shMon Apr1317:25:09 CST2026: sshd status is not running. Mon Apr1317:25:09 CST2026: Start sshd success. Mon Apr1317:25:12 CST2026: sshd status is running. Mon Apr1317:25:15 CST2026: sshd status is running.