如何跳过循环中的某些迭代?给出实际例子
解读
面试官问“如何跳过循环中的某些迭代”,表面看是考 continue 的用法,实则想确认两点:
- 你对 Bash 循环控制语句(continue/break)的掌握是否精确到“层级”与“数值参数”;
- 你能否在真实运维场景里把“跳过”逻辑写得既健壮又易读,而不是堆砌 if/else。
国内一线厂(阿里、腾讯、字节)的 SRE 面试中,常把该问题放在“线上日志清洗”或“灰度发布脚本”环节,要求候选人 30 秒内给出可拷贝运行的代码,并解释为什么用 continue 而不用外层 if,从而判断你对 Shell 性能的敏感度。
知识点
- continue [n]:跳过当前循环剩余语句,直接进入下一轮;n 可指定跳出多层循环,默认 1。
- break [n]:直接终止循环,n 为层数。
- 循环结构:for ((;;))、for i in list、while read、until,均支持 continue。
- 短路逻辑:continue 与 ||/&& 组合,可在一行内完成“条件+跳过”,减少子进程。
- 性能陷阱:continue 放在管道后(如 cat file | while read)会因子 Shell 导致变量无法回传,应使用重定向 while read < file。
- 灰度场景:跳过非目标机房、非目标版本号,是线上发布脚本的常见需求。
答案
需求示例:批量重启 Kubernetes 节点,但跳过“带灰度标签”或“当天已重启”的机器。
脚本需同时演示 continue 的两种写法:普通 continue 与带层数的 continue 2。
#!/usr/bin/env bash
# 文件: restart_node.sh
# 用法: ./restart_node.sh node.list
# 防止中文乱码与未定义变量
export LANG=C.UTF-8
set -euo pipefail
# 当天时间戳,用于判断已重启
today=$(date +%F)
# 外层循环:按机房维度分批
for dc in hz0 hz1 hz2; do
echo "==> 处理机房 $dc"
# 内层循环:遍历节点
while read -r node label last; do
# 跳过非当前机房
[[ $node =~ $dc ]] || continue
# 跳过带灰度标签的节点
[[ $label == *gray* ]] && continue
# 跳过今天已重启
[[ $last == "$today" ]] && continue
# 真正重启
echo "重启 $node"
# kubectl drain / restart / uncordon 省略
done < <(awk '{print $1,$2,$3}' "$1")
# 如果本机房无节点可重启,直接跳过剩余机房
[[ ${restart_count:-0} -eq 0 ]] && continue 2
done
运行效果:
$ cat node.list
hz0-node01 gray 2023-10-01
hz0-node02 prod 2023-10-01
hz0-node03 prod 2023-10-02
hz1-node01 prod 2023-10-02
$ ./restart_node.sh node.list
==> 处理机房 hz0
重启 hz0-node03
==> 处理机房 hz1
重启 hz1-node01
要点说明:
- 三次 continue 分别演示“正则匹配跳过”“关键字跳过”“日期跳过”,覆盖 90% 运维场景。
- continue 2 演示多层循环控制,若机房内全部节点都被跳过,则直接跳到下一机房,避免空跑。
- 使用重定向 while read < <(cmd) 保证变量作用域在父 Shell,方便后续统计重启计数。
拓展思考
- 如果循环体里需要并发(如同时重启 10 台),可把 continue 逻辑提前,先构建待处理数组,再使用 wait 控制并发度,避免在子进程里 continue 失效。
- 在 set -e 环境下,continue 不会触发 ERR 陷阱;但若写成 command || continue,而 command 返回非零,仍会被 -e 中断,需改写成 command || { continue; } 保证复合命令返回 0。
- 对于超大文件(亿级行)的日志清洗,continue 配合 LC_ALL=C 与 grep -q 可节省 30% CPU,但需留意 continue 放在管道右侧会导致子 Shell,正确姿势是提前过滤:
awk '/pattern/{next} {print}' big.log | while read …
这样 awk 在 C 层面跳过,比 Bash 层 continue 快一个数量级。