当前位置: 首页 > news >正文

20260413 if while 语句

一、IF 语句

1.1 语法

1.1.1 单分支语法

# 单分支if条件判断;thencommandfiif条件判断thencommandfi条件判断&&command

1.1.2 双分支语法

# 单分支if条件判断;thencommand1elsecommand2fi条件判断&&command1||command2

1.1.3 多分支语法

# 单分支if条件1判断;thencommand1elif条件2判断;thencommand2elsecommand3fi

1.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清单docommanddone

2.2.2 C语言格式语法

for((num=1;num<=10;num++))doecho$numdone# 执行效果如下12345678910

2.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=55

2.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.jpg

2.2.4 示例3:批量创建用户

公司新入职一批员工,需要为这些员工创建账号。

  1. 员工姓名清单保存在staff.txt中,每行一个。

  2. 为每个员工创建一个初始密码,初始密码是8位随机值,要求登录后必须修改密码。

  3. 创建的结果要保存到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: 594d0504bd

2.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 总结:$() $[] ${}

  1. $() :命令替换
  2. $[]:数值计算
  3. ${}:变量替换

三、while/until

条件满足或者不满足,一直运行。

3.1 语法

3.1.1 while

条件满足,一直运行。

while条件判断docommanddone

3.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服务,实现以下功能:

  1. 如果sshd服务没有运行,则报告sshd服务状态到/tmp/sshd_status.log日志;同时启动sshd服务,启动的结果也写入/tmp/sshd_status.log日志。
  2. 如果sshd服务正常运行,则报告sshd服务状态,并写入/tmp/sshd_status.log日志
  3. 每隔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.
http://www.jsqmd.com/news/641719/

相关文章:

  • Python3.7.8安装指南:从下载到环境配置的完整流程
  • 零基础学化妆|3家靠谱培训学校实测!小白闭眼冲不踩坑 - 品牌测评鉴赏家
  • 为什么90%的AI团队还在用“伪元学习”?:SITS2026闭门报告首次公开元学习能力成熟度评估矩阵(含自测工具包)
  • 电竞椅哪个牌子质量好?傲风M6Pro,告诉你什么是“开挂式”舒适
  • 昆明美甲培训怎么选不踩坑?4家正规机构实测推荐,零基础/就业/创业全覆盖 - 品牌测评鉴赏家
  • 像素时装锻造坊应用场景:独立电影概念设计中的像素化分镜草图生成
  • 美妆小白必看!揭秘专业化妆培训学校如何选 - 品牌测评鉴赏家
  • 模仿学习不是“抄动作”,而是重建认知链——AIAgent中意图-动作-反馈三元耦合机制(仅限头部AI团队内部使用的建模框架)
  • 从零搭建LuckFox RK3576嵌入式开发环境:一站式工具链配置指南
  • I2C协议 - 优雅的代价:深入开漏总线、时钟延展与多主仲裁的脆弱平衡
  • 高胜率却总亏光盈利?投资者如何避开马丁策略的风控盲区
  • 实测不踩坑|2026美甲培训机构TOP5推荐,零基础/创业者直接抄作业 - 品牌测评鉴赏家
  • 答辩PPT救星!百考通AI助你30分钟高效搞定,告别熬夜
  • 小程序不同方式获取参数
  • 【C++11】Cyber骇客的覆写协议与基因锁 ——【C++11 新增的类的功能】C++11中新增的类的功能有哪些?有什么变化?此文助你破局!!!
  • LanzouAPI技术实现:蓝奏云直链解析的逆向工程方案
  • LangChain实战指南:Model I/O与Prompt模板的深度解析
  • 深入理解 Linux 打印体系:CUPS、驱动、ULD 与 Docker 容器化
  • 3家优质美甲进修班推荐,适配不同需求从业者 - 品牌测评鉴赏家
  • 社会韧性正在被AIAgent悄悄稀释?SITS2026压力测试揭示4类隐性系统性风险
  • AI 写作不是抄袭!订阅号合规发文实用技巧
  • 仅剩72小时窗口期!HuggingFace即将下线v4.42前向兼容接口,多模态模型加速部署必须赶在Transformer 4.43发布前完成这5项关键迁移
  • 耐达讯自动化CAN转EtherCAT网关:3步配置,赋能电机启动器智能化升级
  • 机场接入调度平台
  • c#如何使用ModbusRTU_c#ModbusRTU快速上手实战教程
  • 河南化妆培训学校哪家好?2026实测推荐,零基础也能避坑躺赢 - 品牌测评鉴赏家
  • 论文破局:告别本科写作焦虑,百考通AI 全流程辅助指南
  • 联发科手机传感器功耗优化实战:手把手教你理解MTK SensorHub与CHRE协同工作原理
  • 高通 ISP pipeline
  • 机器人手臂相机应用全解析:从安装到标定的关键考量