画面:一行
cp $f "$dst",旁边的 echo 输出看起来一切正常,但命令报错。旁白:echo 告诉你的是你以为的值,set -x 告诉你的是 Bash 真正执行的参数。
set -x + 自定义 PS4(${BASH_SOURCE}:${LINENO}:${FUNCNAME})读懂执行轨迹,用 BASH_XTRACEFD 把轨迹单独写入文件,用 caller 打印调用栈,用 bash -n 和 trap … DEBUG 做语法检查与单步观察。.shellcheckrc 做有理由的抑制。main 函数、:: 包分隔符、局部变量声明与赋值分开等)。run、assert_success、assert_output、setup/teardown、每个测试独立的临时目录、通过 PATH 注入测试替身(stub)。time / hyperfine 量化收益。/bin/sh)、macOS 自带 Bash 3.2、BusyBox ash 的差异,用 checkbashisms 与 shellcheck -s sh 检查可移植性。test/*.bats 测试套件、Makefile/justfile(lint / fmt / test)、GitHub Actions 流水线(固定版本的 ShellCheck + shfmt -d + bats)、VERSION 文件与发布 tarball。| # | 时间 | 模块 | 核心内容 | 动画 / 交互 | 实验(~/bashlab) |
|---|---|---|---|---|---|
| 0 | 课前 | 准备:测试与 CI 工具链 | 安装 ShellCheck、shfmt、bats-core 与辅助库、checkbashisms、hyperfine;获取 opsctl 起点代码 | 环境自检 | check-tools.sh |
| 1 | 00–06 | 调试:set -x、PS4、BASH_XTRACEFD 与 caller | xtrace 原理、PS4 展开与层级前缀、轨迹重定向、caller 调用栈、bash -n、trap DEBUG/ERR | xtrace 单步播放器(PS4 实时展开、调用栈) | 给 opsctl 加 OPSCTL_TRACE=1 开关 |
| 2 | 06–13 | 静态检查:ShellCheck 规则与抑制 | 常见 SC 代码、严重级别、指令、.shellcheckrc、可选检查、输出格式 | 核心动画:ShellCheck 逐条发现并修复问题 | 修复 deploy-old.sh 的 10 处告警 |
| 3 | 13–21 | 格式与风格:shfmt 与风格指南 | shfmt 选项与 EditorConfig、-d/-l/-w、Google Shell Style Guide 关键规则 | shfmt 选项实时预览 | 为 opsctl 配置 .editorconfig 并格式化 |
| 4 | 21–28 | 测试:bats-core、断言与测试替身 | bats 执行模型、run、bats-assert、setup/teardown、临时目录、PATH 替身 | 核心动画:一次 bats 运行(setup → run → 断言 → teardown) | 为 opsctl 写 21 个测试(并发现一个真实问题) |
| 5 | 28–35 | 性能:避免子 Shell、内建优先与剖析 | fork/exec 成本、命令替换、参数展开、printf -v、time/TIMEFORMAT、hyperfine、EPOCHREALTIME 计时 | fork 计数器:同一任务的三种写法 | 日志处理函数提速 50 倍 |
| 6 | 35–42 | 可移植性:POSIX sh、dash、Bash 3.2 与 BusyBox | bashism 清单、dash、macOS Bash 3.2、BusyBox ash、checkbashisms、版本守卫 | 可移植性矩阵:特性 × Shell | 用容器在 bash:3.2 / busybox 上跑脚本 |
| 7 | 42–50 | 什么时候不该用 Bash:迁移到 Python / Go 的信号 | 复杂度信号、数据结构、错误处理、并发、跨平台;迁移策略 | “该换语言了吗?”打分器 | 新建 codes 子命令:awk 与 Python 双实现,用同一套测试对拍 |
| 8 | 50–60 | opsctl v1.0:测试、CI 与发布 | 测试套件、Makefile/justfile、GitHub Actions、VERSION、tarball 与校验和 | CI 流水线模拟器 + 交互排障树 | 发布 opsctl-1.0.0.tar.gz |
| — | 课后 | 速查表 · 综合实验 | 接手一个“祖传脚本”:加测试、修告警、做可移植、接 CI | 结业测验(12 题) | 综合实验 |
| 目标技能 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | 关键命令 | 实验 |
|---|---|---|---|---|---|---|---|---|---|---|
| 执行追踪与调用栈 | ✓ | · | · | ✓ | ✓ | · | · | ✓ | set -x、PS4、BASH_XTRACEFD、caller | M1 |
| 静态分析与抑制策略 | · | ✓ | ✓ | · | · | ✓ | · | ✓ | shellcheck -x -S、.shellcheckrc | M2、M8 |
| 格式化与风格规范 | · | ✓ | ✓ | · | · | · | · | ✓ | shfmt -d、.editorconfig | M3、M8 |
| 自动化测试与替身 | · | · | · | ✓ | · | ✓ | ✓ | ✓ | bats、run、assert_output | M4、M8 |
| 性能剖析与优化 | ✓ | · | · | · | ✓ | · | ✓ | · | time、hyperfine、strace -c -f | M5 |
| 可移植性(POSIX / 旧版本 / BusyBox) | · | ✓ | ✓ | · | · | ✓ | ✓ | ✓ | checkbashisms、shellcheck -s sh、dash -n | M6 |
| 技术选型(何时换语言) | · | · | ✓ | · | ✓ | ✓ | ✓ | · | — | M7 |
| CI 与发布 | · | ✓ | ✓ | ✓ | · | · | · | ✓ | make check、git archive、sha256sum | M8、综合实验 |
| 主题 | 为什么不在本课 | 去哪里学 |
|---|---|---|
| GitHub Actions 的完整语法(矩阵、缓存、环境、OIDC、可复用工作流) | 本课只写一个最小可用的检查流水线 | GitHub 8 小时 |
| GitLab CI / Jenkins 中运行同样的检查 | 思路相同:调用 make check | GitLab 8 小时、Jenkins 8 小时 |
| 多台主机的配置收敛与幂等部署 | 超出“脚本”的边界,应交给配置管理工具(见 M7) | Ansible 8 小时 |
| 严格模式、trap、锁、重试的原理 | 第 4 课已讲,本课直接使用 | 第 4 小时 |
| Python / Go 语言本身 | M7 只讲“何时迁移、如何迁移” | 各语言官方教程 |
| Bash 面试题与生产问题合集 | 集中在第 8 课 | 第 8 小时 |
~/bashlab 内进行。bash 5.3-2ubuntu1;上游补丁已到 5.3.20)。工具版本:ShellCheck 0.11.0(2025-08-03,Ubuntu 26.04 apt 同版本)、shfmt 3.14.1(2026-09-06;Ubuntu 26.04 apt 为 3.12.0)、bats-core 1.14.0(2026-07-21;Ubuntu 26.04 apt 为 1.13.0)、bats-assert 2.2.4、bats-support 0.3.0、hyperfine 2.0.0(apt 为 1.19.0)、dash 0.5.12(Ubuntu 26.04 与 Debian 13 的 /bin/sh)、BusyBox 1.37.0。凡是标注“实际运行结果(Bash 5.2 / dash,Git for Windows)”的输出都在本机真实执行过;其余输出(尤其是 ShellCheck、shfmt、bats 的输出)标注为“示例”,格式来自上游文档与源码,细节以实际为准。~/bashlab,并运行过 ~/bashlab/make-data.sh 生成 ~/bashlab/data/(servers.csv、access.log 等)。可选环境:Linux 课的 linuxlab 虚拟机、WSL2、macOS + Homebrew bash,或容器 docker run --rm -it -v "$PWD":/work -w /work bash:5.3。bin/opsctl、lib/log.sh(log::info/warn/error 写 stderr)、lib/util.sh(util::die、util::require_cmd)、lib/cmd_*.sh(每个子命令一个文件,函数 cmd::<name>)、etc/opsctl.conf、test/。退出码约定:0 成功、1 一般错误、2 用法错误、3 依赖缺失。sudo apt update sudo apt install -y shellcheck shfmt bats bats-support bats-assert devscripts hyperfine busybox # devscripts 很大,只需要 checkbashisms 时也可以只装它: # sudo apt install -y --no-install-recommends devscripts
Ubuntu 26.04(resolute)仓库版本:shellcheck 0.11.0、shfmt 3.12.0、bats 1.13.0、bats-assert 2.2.4、bats-support 0.3.0、devscripts 2.26.7(提供 /usr/bin/checkbashisms)、hyperfine 1.19.0、busybox 1.37.0。apt 安装的 bats 辅助库位于 /usr/lib/bats/bats-assert/ 与 /usr/lib/bats/bats-support/,测试里可以用 bats_load_library 加载(M4)。
brew install bash shellcheck shfmt bats-core hyperfine /opt/homebrew/bin/bash --version | head -1 # Intel Mac 为 /usr/local/bin/bash /bin/bash --version | head -1 # 系统自带的仍是 3.2.57,不要删除它
bats-support / bats-assert 在本课用 git 子模块放进项目(见第 3 步),所以 macOS、Linux、CI 三处的加载方式完全一致,不依赖系统包。
cd ~/bashlab/opsctl docker run --rm -v "$PWD":/mnt -w /mnt koalaman/shellcheck:v0.11.0 -x bin/opsctl lib/*.sh docker run --rm -v "$PWD":/mnt -w /mnt mvdan/shfmt:v3.14.1 -d bin/opsctl lib test docker run --rm -v "$PWD":/code bats/bats:1.14.0 test docker run --rm -v "$PWD":/w -w /w bash:3.2 bash bin/opsctl help # 可移植性实验用(M6)
lib/*.sh 的通配符由主机的 Shell 展开,然后作为参数传进容器——路径都是相对路径,所以在容器里同样有效。镜像标签 koalaman/shellcheck:v0.11.0、mvdan/shfmt:v3.14.1、bats/bats:1.14.0、bash:3.2、bash:5.3、busybox:1.37 均于 2026-11-17 在 Docker Hub 核实存在。本课不重写 opsctl,而是给第 3–6 课已经写好的代码加上测试、门禁与发布流程。如果你没有上一课的成果,起点代码按顺序取自:第 3 课综合实验(v0.1:入口、log、util、config、servers、config 子命令、etc/opsctl.conf)→ 第 4 课模块 8(v0.2:新的 bin/opsctl 与 lib/log.sh、追加到 lib/util.sh 的 v0.2 函数、cmd_export.sh、cmd_doctor.sh、test/flaky.sh)→ 第 5 课模块 8(lib/cmd_logs.sh、lib/logs_report.awk、配置键 logs_top/logs_format)→ 第 6 课模块 8(v0.3:版本号、8 个新配置键、cmd_health.sh、cmd_backup.sh、cmd_deploy.sh)。编写本课时把这四课的代码从课件中逐段提取出来,按顺序重建了 v0.3.0,并在本机 Bash 5.2 上实际运行核对了下表的每一项:
| 接口 | 行为(本机实测) | 退出码 |
|---|---|---|
bin/opsctl → opsctl::main | 版本守卫要求 Bash ≥ 4.4;之后 set -Eeuo pipefail + inherit_errexit + util::setup_traps;全局选项 -c/--config、-v、-h、-V;按名字 source lib/cmd_<name>.sh 并调用 cmd::<name>;help 从 # opsctl-summary: 自动生成(8 个子命令都有) | 未知子命令 2;无参数把用法打印到 stderr 并返回 2 |
lib/log.sh(v0.2) | log::debug/info/warn/error 写 stderr,格式 时间 LEVEL opsctl[PID]: 消息;stderr 是终端且未设 NO_COLOR 时着色;OPSCTL_LOG_FILE 另存一份 | — |
lib/util.sh | EX_OK/EX_ERR/EX_USAGE/EX_DEP、util::die <msg> [code=1]、util::usage_error(→ 2)、util::require_cmd(→ 3)、util::csv_split、util::retry <次数> <初始秒> <命令…>(指数退避 + 全抖动,2/126/127 不重试)、util::lock、util::mktemp_dir、util::cleanup_add | 1 / 2 / 3 |
lib/config.sh | 优先级:命令行 > 环境变量 OPSCTL_<KEY> > etc/opsctl.conf > 默认值;命令行覆盖了不同的环境变量值时只在 -v 下打印一行 DEBUG;键包括 env、data_dir、output、logs_*、health_*、backup_*、deploy_* | — |
opsctl servers list [-e ENV] [-o table|tsv] | 读取 <data_dir>/servers.csv(测试中用 OPSCTL_DATA_DIR 指向夹具目录);table 带表头,tsv 无表头 | 非法 env 2;文件不可读 1 |
opsctl logs report [--top N] [--format text|tsv] [FILE|-] | 单次 awk 扫描(lib/logs_report.awk);tsv 第一行 metric key value | 无有效行 / 文件不可读 1;非法选项值 2 |
opsctl health [-t SEC] [-r N] [-e CODE] URL | health::probe 用 curl -sS -o /dev/null -w '%{http_code} %{time_total}' --connect-timeout T --max-time 2T -- URL,由 util::retry N 1 重试;日志 health ok: … code=200 / health fail: … code=000 curl_rc=7 / giving up after N attempts;也读 OPSCTL_HEALTH_RETRIES 等 | 健康 0;重试耗尽 1;缺 URL、非 http(s)、未知选项 2;缺 curl 3 |
v1.0 唯一的入口改动:版本号改由 VERSION 文件提供(发布流程 M8 以它为唯一来源)。第 6 课把入口中的 readonly OPSCTL_VERSION="0.2.0" 改成了 "0.3.0";下面的 sed 把这一行换成读取文件(对带或不带 readonly 的写法都适用):
cd ~/bashlab/opsctl echo 0.3.0 > VERSION sed -i -E 's/^(readonly +)?OPSCTL_VERSION=.*/OPSCTL_VERSION=$(<"$OPSCTL_HOME\/VERSION") || exit 1\nreadonly OPSCTL_VERSION/' bin/opsctl grep -n 'OPSCTL_VERSION' bin/opsctl | head -3 bin/opsctl -V # 测试夹具:一个独立的小数据目录(含带引号逗号的字段) mkdir -p test/fixtures/data cat > test/fixtures/data/servers.csv <<'EOF' name,env,region,ip,role web-dev-1,dev,canadacentral,10.0.1.10,web web-stg-1,staging,canadacentral,10.0.2.10,web web-prod-1,prod,canadacentral,10.0.3.10,web db-prod-1,prod,ca-central-1,10.0.3.20,"db,primary" EOF
30:OPSCTL_VERSION=$(<"$OPSCTL_HOME/VERSION") || exit 1 31:readonly OPSCTL_VERSION 59:$OPSCTL_PROG $OPSCTL_VERSION - ops toolbox for ~/bashlab opsctl 0.3.0
说明:macOS 的 BSD sed 不支持替换串中的 \n,用编辑器手工改这两行即可。$(<file) 发生在 set -Eeuo pipefail 之后,文件缺失时 || exit 1 给出明确的退出码。夹具故意不用 ~/bashlab/data:测试必须只依赖仓库里的文件,结果才稳定。第 5 课模块 8 已经生成了 test/fixtures/access.sample.log 与 report.expected.tsv(M4 的 logs.bats 会用到);也可以在 setup_file 中用第 1 课的 ~/bashlab/make-data.sh "$BATS_FILE_TMPDIR/data" 生成完整数据集(确定性:12 台服务器,其中 prod 6 台)。
cd ~/bashlab/opsctl git init -q 2>/dev/null || true git submodule add https://github.com/bats-core/bats-core.git test/bats git submodule add https://github.com/bats-core/bats-support.git test/test_helper/bats-support git submodule add https://github.com/bats-core/bats-assert.git test/test_helper/bats-assert # 固定到已核实的版本(可复现) git -C test/bats checkout -q v1.14.0 git -C test/test_helper/bats-support checkout -q v0.3.0 git -C test/test_helper/bats-assert checkout -q v2.2.4 test/bats/bin/bats --version
Bats 1.14.0
这是 bats-core 官方教程推荐的目录布局(test/bats + test/test_helper/…)。别人克隆仓库时需要 git clone --recurse-submodules,或克隆后执行 git submodule update --init。
cat > ~/bashlab/check-tools.sh <<'EOF'
#!/usr/bin/env bash
# 打印本课所需工具的版本;缺失的标为 MISSING
for t in bash shellcheck shfmt bats checkbashisms hyperfine dash busybox; do
if command -v "$t" >/dev/null 2>&1; then
case $t in
bash) v=$BASH_VERSION ;;
shellcheck) v=$(shellcheck --version | awk '/^version:/{print $2}') ;;
shfmt) v=$(shfmt --version) ;;
bats) v=$(bats --version) ;;
checkbashisms) v=$(checkbashisms --version 2>&1 | head -n1) ;;
hyperfine) v=$(hyperfine --version) ;;
busybox) v=$(busybox 2>&1 | head -n1) ;;
*) v=present ;;
esac
printf '%-14s %s\n' "$t" "$v"
else
printf '%-14s MISSING\n' "$t"
fi
done
EOF
chmod +x ~/bashlab/check-tools.sh && ~/bashlab/check-tools.sh
bash 5.3.0(1)-release shellcheck 0.11.0 shfmt v3.12.0 bats Bats 1.13.0 checkbashisms This is checkbashisms, from the Debian devscripts package, version 2.26.7 hyperfine hyperfine 1.19.0 dash present busybox BusyBox v1.37.0 (Ubuntu 1:1.37.0-7ubuntu1) multi-call binary.
$ bin/opsctl -V opsctl 1.0.0 $ OPSCTL_DATA_DIR=test/fixtures/data bin/opsctl servers list --env prod -o tsv web-prod-1 prod canadacentral 10.0.3.10 web db-prod-1 prod ca-central-1 10.0.3.20 db,primary $ bin/opsctl nope; echo "rc=$?" 2026-11-17T09:46:56-0500 ERROR opsctl[446]: unknown command: nope Try 'opsctl --help' for more information. rc=2 $ dash bin/opsctl -V; echo "rc=$?" opsctl: please run with bash, not sh rc=3
rm -rf、make clean)都只作用于 ~/bashlab 内的目录;M2 的反面教材 deploy-old.sh 只用来给 ShellCheck 分析,不要执行。+、++、+++ 前缀分别代表什么。${BASH_SOURCE}、${LINENO}、${FUNCNAME} 的 PS4,并解释为什么必须用单引号赋值。BASH_XTRACEFD 把轨迹与正常 stderr 分开,用 caller / FUNCNAME / BASH_LINENO 打印调用栈。bash -n 做语法检查,用 trap … ERR 报告失败位置,用 trap … DEBUG 单步观察。set -x(等价 set -o xtrace)让 Bash 在执行每条简单命令、for 命令、case 命令、select 命令或算术 for 命令之前,把展开后的命令及其参数打印到 stderr,前面加上 PS4 的展开值(默认 "+ ")。关键在“展开后”:你看到的是参数展开、命令替换、算术展开、单词拆分、路径名展开都完成之后的真实 argv——这正是用 echo 调试经常看不到的东西。
PS4 的第一个字符会按“间接层级”重复:主 Shell 里的命令显示 +,命令替换 $( ) 里的命令显示 ++,嵌套两层显示 +++。所以看到 ++ 就知道这是一个子 Shell 里执行的命令。
| 工具 | 作用 | 何时用 |
|---|---|---|
set -x / bash -x script | 打印展开后的每条命令 | “变量为什么是空的”“参数为什么被拆成两个” |
set -v | 打印读入的原始源码行(未展开) | 与 -x 对照,看展开前后差异 |
PS4 | xtrace 行前缀,每次打印前都会展开 | 加上文件、行号、函数、时间戳 |
BASH_XTRACEFD(Bash ≥ 4.1) | 把 xtrace 写到指定的文件描述符 | 轨迹太多、不想污染 stderr 或日志 |
caller [n]、FUNCNAME、BASH_SOURCE、BASH_LINENO | 调用栈信息 | 在 die / ERR trap 中打印“谁调用了我” |
bash -n script | 只解析不执行(noexec) | 提交前、部署前的语法检查 |
trap '…' DEBUG | 每条简单命令执行前运行 | 单步观察、简单剖析、记录 $BASH_COMMAND |
trap '…' ERR + set -E | 命令返回非零(且不在条件上下文)时运行 | 报告失败的命令与位置 |
echo 调试需要改代码、容易漏、而且看到的是你以为的值。xtrace 看到的是 Bash 实际传给命令的参数,例如 rm -rf $dir/* 在 dir 为空时,xtrace 会清楚地显示 + rm -rf /bin /boot …——这是任何 echo 都很难替你暴露的。配合 PS4 的文件与行号,大型脚本里也能直接跳到出错位置。
export PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
${LINENO} 会在赋值那一刻被展开成固定数字,之后每一行都显示同一个行号。${BASH_SOURCE[0]##*/} 去掉目录只留文件名;被 source 的库文件会显示库的文件名。${FUNCNAME[0]:-main}:顶层代码不在函数里,FUNCNAME 为空,用默认值 main 占位。${EPOCHREALTIME}(Bash ≥ 5.0)得到微秒时间戳,做粗略剖析(M5)。export 后,用 bash -x 启动的子脚本也会继承这个 PS4;但 Bash 在以 root 身份启动时不会从环境继承 PS4(安全原因),root 脚本要在脚本内部设置。bash -n,或 shfmt -d(M3,解析更严格)。set -x … set +x,避免几千行噪声。OPSCTL_TRACE=1)+ BASH_XTRACEFD 写到文件,事后分析。util::die 或 ERR trap 里打印调用栈。| echo / printf | set -x + PS4 | trap DEBUG | bashdb(外部调试器) | |
|---|---|---|---|---|
| 需要改代码 | 是,到处加 | 一行或环境变量 | 一行 | 否 |
| 看到展开后的参数 | 只看到你打印的 | 是 | 通过 $BASH_COMMAND(展开前) | 是 |
| 断点 / 单步 | 否 | 否 | 可模拟 | 是 |
| CI / 生产可用 | 是 | 是(注意泄密) | 慎用(开销大) | 基本不用 |
echo "prod: 2" 显示为 echo 'prod: 2'。② “bash -n 通过就没有语法问题”——它只解析不执行,eval 的字符串、被 source 的文件、命令替换里的内容只在运行时才解析(命令替换的内容在 Bash 5.2+ 会提前解析,但 source 的文件不会)。③ “set -x 很安全”——它会把密码、令牌原样打到日志里,生产与 CI 中必须先 set +x 再处理机密。④ “$BASH_COMMAND 是展开后的命令”——它是即将执行的命令的源码文本,变量尚未展开。caller i 输出的就是“第 i 层调用者”的行号、函数名和文件(行号来自实验 1 的实际运行,加入追踪开关后的第 3 课代码;你的代码行号会不同)左边是一个 9 行的小脚本。选择 PS4 方案和轨迹去向,然后“下一步”:每一步高亮正在执行的行,显示这一步产生的 xtrace 行(按所选 PS4 实时展开,命令替换里的命令带两个 +),右边显示此刻的调用栈(FUNCNAME / BASH_LINENO)和三个输出流。轨迹内容与本机 Bash 5.2 实际运行一致(时间戳为示例)。
| 命令 / 变量 | 作用 | 说明 |
|---|---|---|
bash -x script.sh args | 对整个脚本开启 xtrace | 不用改脚本;bash -xv 同时打印原始行 |
set -x … set +x | 只追踪一段 | { set +x; } 2>/dev/null 可以不打印 set +x 本身 |
PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: ' | 轨迹前缀 | 单引号!首字符按嵌套层级重复 |
exec {fd}>trace.log; BASH_XTRACEFD=$fd | 轨迹写入文件 | Bash ≥ 4.1;取消设置或设为空串恢复写 stderr |
caller / caller N | 当前调用者 / 第 N 层调用者 | 无参数:行号 文件;带 N:行号 函数 文件;越界返回非零 |
bash -n script.sh | 语法检查 | 退出码 0 表示语法正确;可对多个文件循环检查 |
trap 'cmd' DEBUG | 每条简单命令前执行 | 函数内默认不继承,需要 set -T(functrace) |
trap 'cmd' ERR | 命令失败时执行 | 函数与子 Shell 内需要 set -E(errtrace) |
$BASH_COMMAND | 正在执行(或刚失败)的命令文本 | 在 DEBUG/ERR trap 中最有用 |
declare -p var | 精确打印变量(含类型、数组) | 比 echo 更可靠,能看出空串与未设置的区别 |
mkdir -p ~/bashlab/m7 && cd ~/bashlab/m7
cat > dbg.sh <<'EOF'
#!/usr/bin/env bash
export PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
greet() {
local name=$1
printf 'hello %s\n' "$name"
}
set -x
n=2
greet "$n"
set +x
EOF
bash dbg.sh
+ dbg.sh:8:main: n=2 + dbg.sh:9:main: greet 2 + dbg.sh:4:greet: local name=2 + dbg.sh:5:greet: printf 'hello %s\n' 2 hello 2 + dbg.sh:10:main: set +x
bash -c 'PS4="+ "; set -x; a=$(echo $(echo hi)); echo "$a"'
+++ echo hi ++ echo hi + a=hi + echo hi hi
cat > xfd.sh <<'EOF'
exec 5>trace.log
BASH_XTRACEFD=5
PS4='+ ${LINENO}: '
set -x
x=$((1+2))
echo "x=$x"
set +x
EOF
bash xfd.sh; echo "--- trace.log:"; cat trace.log
x=3 --- trace.log: + 5: x=3 + 6: echo x=3 + 7: set +x
注意:手册说明,把 BASH_XTRACEFD 设成 2 之后再 unset 它,会关闭标准错误。不要写 BASH_XTRACEFD=2;需要恢复时直接 unset BASH_XTRACEFD(前提是它指向的是你自己打开的 fd)。
cat > err.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
on_err() {
local rc=$? i
printf 'ERROR rc=%d at %s:%d: %s\n' "$rc" "${BASH_SOURCE[1]}" "${BASH_LINENO[0]}" "$BASH_COMMAND" >&2
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
printf ' at %s (%s:%d)\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]}" "${BASH_LINENO[i-1]}" >&2
done
}
trap on_err ERR
load_conf() { grep -q '^env=' /nonexistent/opsctl.conf; }
start() { load_conf; }
start "$@"
EOF
bash err.sh; echo "rc=$?"
grep: /nonexistent/opsctl.conf: No such file or directory ERROR rc=2 at err.sh:11: grep -q '^env=' /nonexistent/opsctl.conf at load_conf (err.sh:11) at start (err.sh:12) at main (err.sh:13) rc=2
最底下一层的 main 不是你写的函数,而是 Bash 给脚本顶层的名字。没有 set -E 时,ERR trap 不会在函数内部触发,你只能看到 start 返回失败,丢失了真正出错的行。
cat > caller.sh <<'EOF'
die() { local frame=0; while caller $frame; do ((frame++)); done; }
inner() { die; }
outer() { inner; }
outer
EOF
bash caller.sh
printf 'if true; then\n echo hi\n' > bad.sh
bash -n bad.sh; echo "rc=$?"
2 inner caller.sh 3 outer caller.sh 4 main caller.sh bad.sh: line 3: syntax error: unexpected end of file rc=2
Bash 5.3 改进了这类报错,会补充是哪个复合命令没有闭合(例如提示来自第 1 行的 if),具体文字以你的版本为准。
bash -c 'trap '\''echo "DEBUG> $BASH_COMMAND"'\'' DEBUG; a=1; echo $a'
DEBUG> a=1 DEBUG> echo $a 1
OPSCTL_TRACE 开关:在 bin/opsctl 的 readonly OPSCTL_PROG 之后(库加载之前)插入:
cd ~/bashlab/opsctl
python3 - <<'PY'
import pathlib
p = pathlib.Path("bin/opsctl"); s = p.read_text(encoding="utf-8")
add = '''
# 追踪开关:OPSCTL_TRACE=1 写到 stderr;OPSCTL_TRACE=/path/file 写到文件
if [[ -n ${OPSCTL_TRACE:-} ]]; then
export PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
if [[ ${OPSCTL_TRACE} != 1 ]]; then
exec {OPSCTL_TRACE_FD}>>"${OPSCTL_TRACE}"
BASH_XTRACEFD=${OPSCTL_TRACE_FD}
fi
set -x
fi
'''
anchor = "readonly OPSCTL_PROG\n"
if "OPSCTL_TRACE" not in s:
s = s.replace(anchor, anchor + add, 1)
p.write_text(s, encoding="utf-8")
PY
grep -n 'OPSCTL_TRACE' bin/opsctl | head -3
35:# 追踪开关:OPSCTL_TRACE=1 写到 stderr;OPSCTL_TRACE=/path/file 写到文件
36:if [[ -n ${OPSCTL_TRACE:-} ]]; then
38: if [[ ${OPSCTL_TRACE} != 1 ]]; then
也可以用编辑器手工粘贴中间那段。这里用 Python 只是为了“可复制执行”,不依赖 sed 的 GNU/BSD 差异。注意 exec {OPSCTL_TRACE_FD}>>file 让 Bash 自动分配一个 ≥ 10 的空闲 fd。
OPSCTL_TRACE=1 OPSCTL_DATA_DIR=test/fixtures/data bin/opsctl servers list --env prod -o tsv 2>&1 \ | grep -n 'servers::list\|cmd::servers' | head -4
162:+ 1794926908.252304 opsctl:96:opsctl::load_command: declare -F cmd::servers 163:+ 1794926908.252407 opsctl:136:opsctl::main: log::debug 'dispatch: cmd::servers list --env prod -o tsv' 164:+ 1794926908.252436 log.sh:30:log::debug: log::_emit debug 'dispatch: cmd::servers list --env prod -o tsv' 170:+ 1794926908.252619 opsctl:137:opsctl::main: cmd::servers list --env prod -o tsv
第 162 行之前是库加载、util::setup_traps 与 config::init 的轨迹——这就是为什么要按文件/函数过滤。log::debug 在 info 级别下什么也不打印,但它的调用仍然出现在轨迹里。
OPSCTL_TRACE=/tmp/opsctl.trace OPSCTL_DATA_DIR=test/fixtures/data bin/opsctl servers list --env prod -o tsv wc -l < /tmp/opsctl.trace
web-prod-1 prod canadacentral 10.0.3.10 web db-prod-1 prod ca-central-1 10.0.3.20 db,primary 1456
一次只输出两行的调用产生了一千多行轨迹(大部分来自 util::csv_split 的逐字符循环)——这也是 M5 讨论性能的伏笔。
util::die 打印调用栈:把 lib/util.sh 中的 util::die 改为(签名不变:util::die <msg> [code=1]):
util::die() { # util::die <message> [exit_code=1]
local i
log::error "$1"
if [[ -n ${OPSCTL_DEBUG:-} ]]; then
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
printf ' at %s (%s:%d)\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]##*/}" "${BASH_LINENO[i - 1]}" >&2
done
fi
exit "${2:-1}"
}
OPSCTL_DEBUG=1 OPSCTL_DATA_DIR=/nope bin/opsctl servers list; echo "rc=$?"
2026-11-17T09:48:28-0500 ERROR opsctl[399]: cannot read /nope/servers.csv (run ~/bashlab/make-data.sh first?)
at servers::list (cmd_servers.sh:63)
at cmd::servers (cmd_servers.sh:24)
at opsctl::main (opsctl:137)
at main (opsctl:140)
rc=1
最后一层 main 是脚本顶层(第 140 行 opsctl::main "$@"),不是你写的函数。v0.2 起入口有 util::setup_traps,但 util::die 是显式 exit,不会触发 ERR 报告。
for f in bin/opsctl lib/*.sh; do bash -n "$f" || echo "语法错误: $f"; done; echo done
问题:部署脚本在 CI 中每 20 次失败 1 次,本地无法复现。做法:CI 中设置 OPSCTL_TRACE=$RUNNER_TEMP/trace.log,失败时把轨迹作为构件上传;轨迹显示某次 curl 返回 000 后紧接着的 jq 解析了空输入。修复:给 API 调用加重试(第 6 课)并检查 HTTP 状态码。限制:轨迹可能包含令牌——上传前用 sed 打码或在处理机密的代码段 set +x。
问题:有人在生产脚本开头加了 set -x 排错后忘了删除,数据库密码随 mysql -p"$PASS" 的轨迹进入集中日志系统。做法:轮换密码、清理日志;规范改为“只通过环境变量开关追踪”,并让 ShellCheck/代码评审拦截硬编码的 set -x。更好的写法:密码通过文件或标准输入传递(--defaults-extra-file、--password-stdin),这样即使开启追踪也看不到。
问题:一个被 30 个脚本 source 的 lib/util.sh 报“参数为空”,日志里只有库的行号。做法:在 die 中打印 FUNCNAME/BASH_SOURCE/BASH_LINENO 调用栈后,第一次出现就定位到调用方。效果:后续所有脚本的错误都自带栈信息,平均定位时间从“小时”降到“分钟”。
原因:用双引号给 PS4 赋值,${LINENO} 在赋值时就被展开成了固定值。
PS4="+ ${LINENO}: " # 错:赋值时展开
PS4='+ ${LINENO}: ' # 对:每次打印轨迹时展开原因:if/fi、do/done、case/esac、{/} 或引号、heredoc 结束标记没有配对。报告的行号通常是文件末尾,不是真正缺失的位置。
bash -n script.sh shfmt -d script.sh # 报错位置通常更准确(M3) grep -nE '^\s*(if|fi|for|while|until|do|done|case|esac)\b' script.sh # 粗略配对
另一常见原因:Windows 换行(CRLF)导致 heredoc 结束标记变成 EOF\r 而无法匹配;用 file script.sh 检查,sed -i 's/\r$//' script.sh 修复(或在 .gitattributes 中设 *.sh text eol=lf)。
原因:脚本是 CRLF 换行,每行末尾多了 \r,xtrace 会显示为 $'\r'。
bash -x script.sh 2>&1 | grep -m3 $'\r' sed -i 's/\r$//' script.sh
原因:设置过 BASH_XTRACEFD=2 然后 unset BASH_XTRACEFD——Bash 会关闭该 fd,也就是关闭了 stderr。
修复:只把 BASH_XTRACEFD 指向你自己用 exec {fd}>file 打开的 fd;需要恢复时 unset 它(关闭的是你自己的 fd)。
原因:ERR trap 默认不被 Shell 函数、命令替换和子 Shell 继承。
set -E # 等价 set -o errtrace trap 'on_err' ERR
同理,DEBUG 与 RETURN trap 需要 set -T(functrace)才能在函数内生效。另外,处于 if、while 条件、&&/|| 左侧的失败不会触发 ERR(与 set -e 的例外相同,见第 4 课)。
deploy 内部,且不打印 set +x 这一行本身。deploy() {
set -x
# ... 需要追踪的代码 ...
{ set +x; } 2>/dev/null
}PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO} ${FUNCNAME[0]:-main} ${EPOCHREALTIME}: '
# EPOCHREALTIME 需要 Bash ≥ 5.0,单位是秒(小数部分为微秒)① 在 crontab 里临时改为 OPSCTL_TRACE=/tmp/backup.trace /path/backup.sh(或 bash -x),并把 PS4 设为带文件和行号的版本;② 下次运行后在轨迹里找 rm 那一行,看展开后的参数——cron 的环境变量极少(PATH 只有 /usr/bin:/bin,没有你在 .bashrc 里设置的变量),很可能某个变量为空导致 rm -rf "$DIR"/* 变成了 rm -rf /var/backups/* 之类;③ 修复:变量用 ${DIR:?} 防空、脚本里显式设置 PATH 与所需变量;④ 用 ShellCheck(SC2115)在提交时就拦截这类写法(M2)。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
cp $f "$dst",旁边的 echo 输出看起来一切正常,但命令报错。disable、source、source-path、shell、enable),并用 .shellcheckrc 统一项目配置。-S、-f、-x、-o 把 ShellCheck 接入编辑器、Makefile 和 CI。set -e 例外规则。重要程度:★★★★★ShellCheck 是用 Haskell 编写的 Shell 脚本静态分析器:它把脚本解析成语法树(AST),然后对语法树运行数百条规则,找出语法错误、语义陷阱(引号、退出码、作用域)、可移植性问题(在 #!/bin/sh 脚本里用了 bashism)和风格问题。它不执行脚本,所以可以安全地分析 rm -rf 之类的危险代码。每条规则有一个编号:
| 编号段 | 含义 | 例子 |
|---|---|---|
| SC1xxx | 解析器(parser)问题:语法、引号、编码 | SC1091 无法跟随 source 的文件;SC1017 文件含 CR(Windows 换行) |
| SC2xxx | 通用语义问题(最多) | SC2086 未加引号;SC2155 声明与赋值合写 |
| SC3xxx | 在 sh(POSIX)方言中使用了不可移植的特性 | SC3010 [[ ]];SC3043 local;SC3030 数组 |
| 级别 | 含义 | 典型 |
|---|---|---|
| error | 几乎肯定是 bug 或语法错误 | SC2045 遍历 ls 输出、SC1073 解析失败 |
| warning | 很可能导致错误行为 | SC2164 cd 失败未处理、SC2155、SC2046、SC2115、SC2034 |
| info | 在某些输入下会出问题 | SC2086 未加引号、SC1091 |
| style | 更好的写法 | SC2006 反引号、SC2181 用 $? 判断 |
-S warning 表示只报告 warning 及以上(error + warning)。很多团队的 CI 门禁从 -S warning 开始,再逐步收紧到默认的 style 级别。
| 代码 | 问题代码 | 会发生什么 | 修复 |
|---|---|---|---|
| SC2086 | cp $f /backup | f="my file.txt" 被拆成两个参数;f="*" 被通配展开 | cp -- "$f" /backup |
| SC2046 | chmod 644 $(find . -name '*.conf') | 命令替换的结果被按空白拆分并通配 | find … -exec chmod 644 {} + 或 mapfile -d '' |
| SC2155 | local v=$(cmd) / export V=$(cmd) | 退出码是 local/export 的(总是 0),cmd 的失败被吞掉,set -e 也不触发 | 先 local v,再 v=$(cmd) |
| SC2164 | cd $dir | cd 失败后继续在当前目录执行后面的 rm | cd -- "$dir" || exit |
| SC2181 | cmd; if [ $? -ne 0 ] | 中间插入任何命令(如日志)就会覆盖 $?;且 set -e 下 cmd 失败根本到不了 if | if ! cmd; then |
| SC2034 | unused=1 | 变量拼写错误(VERISON)或死代码 | 删除、修正拼写,或 export |
| SC2045 | for f in $(ls *.log) | 文件名含空格、换行时出错 | for f in ./*.log |
| SC2115 | rm -rf $dir/* | dir 为空时变成 rm -rf /* | rm -rf -- "${dir:?}"/* |
| SC2006 | `cmd` | 嵌套和转义难读 | $(cmd) |
| SC1091 | source lib/x.sh | ShellCheck 没有跟随(分析)被 source 的文件 | -x + # shellcheck source=… |
.shellcheckrc(从被检查文件所在目录向上查找,也会读用户家目录的配置),内容就是去掉 # shellcheck 前缀的指令。enable= 打开,shellcheck --list-optional 列出全部;0.11.0 起 SC2002(无用的 cat)改为默认关闭的可选项。编辑器(VS Code 的 ShellCheck 扩展、Vim ALE、Neovim LSP 通过 bash-language-server)→ 提交前(pre-commit 钩子)→ CI 门禁(M8)。越早发现越便宜。
| ShellCheck | bash -n | shfmt | checkbashisms | |
|---|---|---|---|---|
| 发现语法错误 | 是 | 是 | 是(更严格) | 部分 |
| 发现语义陷阱(引号、退出码) | 是 | 否 | 否 | 否 |
| 可移植性 | 是(SC3xxx) | 否 | 按方言解析 | 是(专项) |
| 改写代码 | 部分可自动修复(-f diff) | 否 | 格式化 | 否 |
# shellcheck disable=all 最省事”——全局抑制会让新代码也失去保护;应该逐条抑制并写理由。④ “-x 只是个可选项”——不加 -x(或 external-sources=true)时,被 source 的库里定义的变量和函数对 ShellCheck 不可见,会出现大量 SC2154 误报。样例是一个“祖传”部署脚本 deploy-old.sh(只做分析,不要执行)。点击“下一步”:ShellCheck 依次报告每个问题(tty 格式,带插入符 ^ 指向的位置),再点一次“修复”就把这一行改成正确写法,右侧记录剩余告警数。用上方的 -S 按钮切换最低严重级别,观察哪些告警会被过滤。告警文字与 ShellCheck 0.11.0 wiki 一致,输出布局为示例。
shellcheck deploy-old.sh。| 命令 | 作用 | 说明 |
|---|---|---|
shellcheck script.sh | 检查(默认 tty 格式) | 退出码 0 = 无问题,1 = 有问题 |
shellcheck -x bin/opsctl lib/*.sh | 跟随 source 的文件 | 等价于 rc 中 external-sources=true |
-S error|warning|info|style | 最低严重级别 | CI 门禁常用 -S warning 起步 |
-e SC2086,SC2034 / -i SC2086 | 排除 / 只包含某些代码 | 命令行级别,比指令范围大,慎用 |
-s sh|bash|dash|ksh|busybox | 指定方言 | 没有 shebang 的库文件用 # shellcheck shell=bash 更好 |
-f tty|gcc|json1|checkstyle|diff|quiet | 输出格式 | gcc 适合编辑器跳转;checkstyle 适合 CI 报表;diff 可自动修复 |
-o all / --list-optional | 启用 / 列出可选检查 | 如 require-variable-braces、check-extra-masked-returns |
-P SCRIPTDIR | source 搜索路径 | 等价指令 source-path= |
--norc | 忽略 .shellcheckrc | 排查“为什么本地和 CI 结果不同” |
shellcheck -W 0 --wiki-link-count=0 | 不打印 wiki 链接 | 精简输出 |
mkdir -p ~/bashlab/m7 && cd ~/bashlab/m7 cat > deploy-old.sh <<'EOF' #!/bin/bash src=$1 dest=/srv/releases/`date +%s` unused_count=0 cd $dest for f in $(ls $src/*.tar.gz); do cp $f . done tar xzf app.tar.gz if [ $? -ne 0 ]; then echo "extract failed"; exit 1; fi export VERSION=$(cat $src/VERSION) chmod 644 $(find . -name '*.conf') rm -rf $dest/old/* EOF shellcheck -f gcc deploy-old.sh
deploy-old.sh:3:6: note: Use $(...) notation instead of legacy backticks `...`. [SC2006]
deploy-old.sh:4:1: warning: unused_count appears unused. Verify use (or export if used externally). [SC2034]
deploy-old.sh:5:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
deploy-old.sh:5:4: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:6:10: error: Iterating over ls output is fragile. Use globs. [SC2045]
deploy-old.sh:6:16: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:7:6: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:10:6: note: Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?. [SC2181]
deploy-old.sh:11:8: warning: Declare and assign separately to avoid masking return values. [SC2155]
deploy-old.sh:11:23: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:12:11: warning: Quote this to prevent word splitting. [SC2046]
deploy-old.sh:13:8: warning: Use "${var:?}" to ensure this never expands to /* . [SC2115]
deploy-old.sh:13:8: note: Double quote to prevent globbing and word splitting. [SC2086]
gcc 格式把 info 与 style 都显示为 note;tty 格式会显示 SC2086 (info)、SC2006 (style) 这样的精确级别。列号以实际为准。
cat > deploy-fixed.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
src=${1:?用法: deploy-fixed.sh SRC_DIR}
dest=/srv/releases/$(date +%s)
mkdir -p -- "${dest}"
cd -- "${dest}" || exit 1
for f in "${src}"/*.tar.gz; do
[[ -e ${f} ]] || continue # 没有匹配时通配符保持原样
cp -- "${f}" .
done
if ! tar xzf app.tar.gz; then
echo "extract failed" >&2
exit 1
fi
VERSION=$(<"${src}/VERSION")
export VERSION
find . -name '*.conf' -exec chmod 644 {} +
rm -rf -- "${dest:?}/old/"*
EOF
shellcheck deploy-fixed.sh && echo "ShellCheck: clean"
ShellCheck: clean
shellcheck -S warning deploy-old.sh | grep -c '^In ' # 只算 error+warning shellcheck -f diff deploy-old.sh > fix.patch # 只包含“可自动修复”的建议 git apply --check fix.patch 2>/dev/null || patch -p1 --dry-run < fix.patch shellcheck -f json1 deploy-old.sh | jq -r '.comments[] | "\(.line):\(.code) \(.level)"' | head
-f diff 只覆盖部分规则(例如加引号),像 SC2045、SC2155 这类需要改结构的仍要手工修复。
# 单条命令抑制,并写明理由
# shellcheck disable=SC2086 # RSYNC_OPTS 是有意按空格拆分的选项列表
rsync ${RSYNC_OPTS} -- "$src" "$dst"
# 告诉 ShellCheck 动态 source 的真实文件
# shellcheck source=lib/log.sh
source "${OPSCTL_HOME}/lib/log.sh"
# 没有 shebang 的库文件,第一行声明方言
# shellcheck shell=bash
cat > ~/bashlab/opsctl/.shellcheckrc <<'EOF' # opsctl 项目的 ShellCheck 配置(从被检查文件的目录向上查找) external-sources=true source-path=SCRIPTDIR # 可选检查(默认关闭):不要用 which(用 command -v) enable=deprecate-which # 想更严格时再逐个打开,例如 enable=add-default-case(case 必须有 *) 分支) EOF cd ~/bashlab/opsctl && shellcheck bin/opsctl lib/*.sh && echo "opsctl: clean"
cd ~/bashlab/m7 shellcheck -f json1 deploy-old.sh | jq -r '.comments[] | "\(.level) SC\(.code)"' | sort | uniq -c | sort -rn
5 info SC2086
1 warning SC2164
1 warning SC2155
1 warning SC2115
1 warning SC2046
1 warning SC2034
1 style SC2181
1 style SC2006
1 error SC2045
没有 jq 时用 shellcheck -f gcc deploy-old.sh | grep -o 'SC[0-9]*' | sort | uniq -c。
shellcheck -S warning deploy-old.sh,确认数量下降。bash -c 'set -e; f() { local v=$(false); echo "still running, v=[$v]"; }; f'
bash -c 'set -e; f() { local v; v=$(false); echo "not reached"; }; f; echo "rc=$?"'
still running, v=[]
第一行:local 的退出码是 0,false 的失败被吞掉,脚本继续运行。第二行:赋值语句的退出码就是命令替换的退出码,set -e 生效,函数和整个 bash -c 立即退出(所以 rc= 也没有打印)。
mkdir -p ~/bashlab/m7/q && cd ~/bashlab/m7/q touch 'my file.txt' f='my file.txt' ls $f; echo "---"; ls "$f"
ls: cannot access 'my': No such file or directory ls: cannot access 'file.txt': No such file or directory --- 'my file.txt'
.shellcheckrc,然后:
cd ~/bashlab/opsctl shellcheck bin/opsctl lib/*.sh; echo "rc=$?"
第 3 课起的入口已经带有 # shellcheck source-path=SCRIPTDIR/.. 与 # shellcheck source=lib/log.sh 等指令;v0.3 的库与子命令中没有任何 disable 指令(清理改由 util::cleanup_add 登记,而不是在 trap 字符串里展开变量,自然也就不需要抑制 SC2064)——这正是本模块推荐的方向:先改写法,最后才抑制。如果你的第 3–6 课实现有告警,按本模块的表格逐条修复;确实需要保留的写法,用单行指令加理由。
问题:清理脚本 rm -rf $STEAMROOT/* 在变量为空时删除了用户的所有文件——这是 2015 年 Steam for Linux 的真实事故(valve-software/steam-for-linux issue #3671)。做法:ShellCheck 的 SC2115 正是为这类写法设计的;修复为 rm -rf -- "${STEAMROOT:?}"/*,并在脚本开头 set -u。教训:危险命令所在的脚本必须进入 ShellCheck 门禁。
问题:一个有 200 个脚本的仓库首次运行 ShellCheck 出现 3000 多条告警,无法一次修完。做法:① CI 先用 -S error,修完 error 后改为 -S warning;② 只对改动过的文件用默认级别(git diff --name-only origin/main -- '*.sh' | xargs -r shellcheck);③ 每周清理一批 SC2086。效果:两个月后全仓库达到默认级别零告警。
问题:开发者用 # shellcheck disable=SC2086 绕过了一个确实有问题的未加引号变量。做法:团队规定所有 disable 指令必须带 # 理由,并在 CI 中用 grep -rn 'shellcheck disable' --include='*.sh' | grep -v '#.*#' 找出没写理由的指令让评审关注。
原因:默认不跟随 source 的文件。
shellcheck -x bin/opsctl # 或在 .shellcheckrc 写 external-sources=true # 路径是动态的时候,在 source 上方加: # shellcheck source=lib/log.sh
注意:source= 的相对路径按 ShellCheck 的当前工作目录解析,所以要从仓库根目录运行;或者配合 source-path=SCRIPTDIR(以脚本所在目录为基准)。
原因:变量在被 source 的文件里赋值、由环境传入,或拼写错误。
修复:加 -x 让 ShellCheck 看到库;环境变量用 ${VAR:?} 或 ${VAR:-default} 表明意图;真的是外部注入的,用 : "${VAR:?必须设置 VAR}" 在脚本开头声明。
原因:库文件没有 shebang,ShellCheck 不知道该用哪个方言。
sed -i '1i # shellcheck shell=bash' lib/foo.sh # GNU sed;或手工在第一行加入
原因:文件是 Windows 换行(CRLF)。
tr -d '\r' < script.sh > script.tmp && mv script.tmp script.sh printf '*.sh text eol=lf\n*.bats text eol=lf\nbin/* text eol=lf\n' >> .gitattributes
原因:版本不同(例如本地 0.9,CI 0.11 新增了 SC2327–SC2335);或本地用户家目录的 ~/.shellcheckrc 抑制了某些规则。
shellcheck --version | head -2 shellcheck --norc bin/opsctl lib/*.sh # 排除个人配置的影响
修复:CI 与本地使用同一个固定版本(M8 在 CI 中下载 v0.11.0),项目配置只放在仓库的 .shellcheckrc。
git diff --name-only --diff-filter=d origin/main -- '*.sh' | xargs -r shellcheck -x -S warning
local out=$(cd $dir; ls)local out
out=$(cd -- "$dir" && ls) || return
# 更好的做法:不要解析 ls,改用数组:files=("$dir"/*).shellcheckrc 里全局 disable=SC2086,理由是“我们的变量都不含空格”。你怎么回应?不同意全局抑制。① “不含空格”是今天的假设,文件名、用户输入、云资源名明天就可能含空格或通配符字符(*、?、[);② SC2086 同时防止路径名展开,变量值为 * 时后果严重;③ 真正需要拆分的地方(例如选项列表)应改用数组 "${opts[@]}",少数无法改的地方用单行指令加理由。可以接受的折中:CI 先用 -S warning(SC2086 是 info,不会阻塞),同时制定计划逐步修复。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
shfmt -d(检查)、-l(列出)、-w(改写)格式化脚本,理解 -i、-ci、-bn、-sr、-fn、-s 的效果。.editorconfig 保存 shfmt 配置,并知道“命令行一旦给了格式参数,EditorConfig 就会被完全忽略”。.sh 库文件被当作 POSIX 解析。shfmt 是 Daniel Martí(mvdan)用 Go 编写的 Shell 解析器 / 格式化器 / 解释器项目 mvdan.cc/sh 的命令行工具。它把脚本完整解析成语法树,再按统一规则打印回去——所以它既是格式化器,也是一个比 bash -n 更严格的语法检查器(静态解析全部语法,并要求合法的 UTF-8)。支持的方言:bash、posix、mksh、bats、zsh(3.14 起)。
| 选项 | EditorConfig 键 | 效果 |
|---|---|---|
-i N | indent_style / indent_size | 0 = Tab(默认),N > 0 = N 个空格 |
-ci | switch_case_indent(新拼写 case_indent) | case 分支比 case 关键字多缩进一级 |
-bn | binary_next_line | 换行时把 &&、||、| 放到下一行开头 |
-sr | space_redirects | 重定向符号后加空格:> file |
-fn | function_next_line | 函数的 { 放到下一行 |
-kp | keep_padding | 保留用于对齐的空格 |
-s | simplify | 简化代码(例如去掉 $(( $a )) 里多余的 $) |
-ln bash|posix|mksh|bats|zsh | shell_variant(新拼写 language_dialect) | 指定方言;默认 auto |
新旧拼写:3.14 的手册说明旧键名 shell_variant、switch_case_indent 仍被接受;为了同时兼容 Ubuntu 26.04 apt 里的 3.12.0,本课的 .editorconfig 使用旧拼写。
shfmt -d 在 CI 中充当“格式门禁”和“严格语法检查”。在 -ln auto(默认)时:先看文件扩展名(如 .bash、.mksh、.bats);否则看 shebang;都没有则按 bash 处理。但手册特别说明:.sh 扩展名是特例,它意味着 posix,只有合法的 shebang 才能覆盖。opsctl 的 lib/*.sh 没有 shebang,所以会被当作 POSIX 解析,遇到 [[ ]]、local 之外的 bash 语法就报错——解决办法是在 .editorconfig 里为 *.sh 指定 shell_variant = bash。
| 规则 | 原文要点 | opsctl 中的落实 |
|---|---|---|
| 何时用 Shell | 超过 100 行或控制流不直观的脚本,应尽快改用结构化语言 | M7 的迁移信号 |
| 只用 Bash | “Bash is the only shell scripting language permitted for executables.” | #!/usr/bin/env bash |
| 缩进与行宽 | 2 空格、不用 Tab;最长 80 列 | indent_size = 2 |
| 管道换行 | 放得下就写一行;否则每段一行,管道符在行首,缩进 2 空格 | binary_next_line = true |
| 函数命名 | 小写加下划线;库函数可用 :: 作为包分隔符 | log::info、util::die、cmd::servers |
| main 函数 | 包含至少一个其他函数的脚本必须有 main,最后一行 main "$@" | bin/opsctl |
| 局部变量 | 用 local;值来自命令替换时,声明与赋值必须分开 | 对应 SC2155 |
| 测试 | [[ … ]] 优于 [ … ] 与 test | 库内统一 [[ ]](入口的版本守卫除外,见 M6) |
| 命令替换 | 用 $(command),不用反引号 | 对应 SC2006 |
| 错误输出 | 所有错误信息写 STDERR | lib/log.sh 全部 >&2 |
| 文件扩展名 | 可执行文件用 .sh 或无扩展名;库必须用 .sh 且不可执行 | bin/opsctl 无扩展名,lib/*.sh 权限 644 |
| 常量 | 全大写,readonly 或 declare -r | readonly OPSCTL_HOME |
| 工具 | 推荐所有脚本使用 ShellCheck | M2、M8 |
| 其他 | 避免 eval;用数组保存参数列表;读命令输出用进程替换或 readarray 而不是管道到 while | 第 2、3 课 |
Google 风格指南本身没有提到 shfmt;把它的缩进、管道规则映射为 shfmt 选项是本课的做法(-i 2 -bn -ci 是 shfmt 手册中给出的示例组合,与 Google 风格最接近)。
-s 也只做等价简化),不会给变量加引号;语义问题仍然靠 ShellCheck。② “我在 Makefile 里写了 shfmt -i 2 -d,EditorConfig 里的方言设置也会生效”——不会:只要命令行给出任何解析或打印参数,EditorConfig 就被整体忽略。③ “格式化后要逐行人工检查”——shfmt 基于完整的语法树,格式化是保持语义的;但第一次全仓库格式化应该单独一个提交,方便评审与 git blame --ignore-rev。左边是一段格式混乱的输入,右边是 shfmt 的输出。切换选项观察每个选项影响哪些行(被影响的行高亮)。输出按 shfmt 的打印规则模拟,用于理解选项含义;以你本机 shfmt 的实际输出为准。
| 命令 | 作用 | 说明 |
|---|---|---|
shfmt file.sh | 把格式化结果打印到 stdout | 不修改文件 |
shfmt -d . | 格式不同就输出 diff 并以非零退出 | CI 门禁;NO_COLOR=1 关闭颜色 |
shfmt -l . | 列出格式不同的文件(也以非零退出) | 与 -w 组合:shfmt -l -w . |
shfmt -w file… | 原地改写 | 先提交再改写,方便回滚 |
shfmt -f . | 只列出目录中的 Shell 文件 | 按扩展名与 shebang 识别;3.14 新增 --detect exec|all |
shfmt -i 2 -ci -bn | 手册示例组合 | 接近 Google 风格 |
shfmt -ln bash / -p | 强制方言 / POSIX | 会让 EditorConfig 失效 |
shfmt --filename=x.sh < x.sh | 从 stdin 读取时让 EditorConfig 生效 | 编辑器集成用 |
cd ~/bashlab/m7
cat > messy.sh <<'EOF'
#!/usr/bin/env bash
backup(){
local src=$1 dst=$2
if [ -d "$src" ] &&
[ -w "$dst" ];then
tar -czf "$dst/b.tgz" -C "$src" . >"$dst/b.log"
fi
case $3 in
full) echo full;;
*) echo incr;;
esac
}
EOF
shfmt messy.sh | cat -A | head -n 6 # cat -A 让 Tab 显示为 ^I
shfmt -i 2 -ci -bn messy.sh
#!/usr/bin/env bash
backup() {
local src=$1 dst=$2
if [ -d "$src" ] \
&& [ -w "$dst" ]; then
tar -czf "$dst/b.tgz" -C "$src" . >"$dst/b.log"
fi
case $3 in
full) echo full ;;
*) echo incr ;;
esac
}
cat > ~/bashlab/opsctl/.editorconfig <<'EOF'
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
# Shell:2 空格、case 分支缩进、二元运算符放行首(接近 Google 风格)
[*.sh]
indent_style = space
indent_size = 2
# 关键:.sh 默认按 posix 解析,而库文件没有 shebang
# (EditorConfig 只支持整行注释,不要写行尾注释)
shell_variant = bash
switch_case_indent = true
binary_next_line = true
[bin/opsctl]
indent_style = space
indent_size = 2
switch_case_indent = true
binary_next_line = true
[*.bats]
indent_style = space
indent_size = 2
shell_variant = bats
switch_case_indent = true
binary_next_line = true
[{Makefile,*.mk}]
indent_style = tab
EOF
cd ~/bashlab/opsctl
shfmt -d bin/opsctl lib test/*.bats 2>/dev/null; echo "shfmt rc=$?"
shfmt -l -w bin/opsctl lib # 有差异就改写(先 git commit 一次!)
注意:shfmt 读取 EditorConfig 时不能再给任何格式参数,所以 Makefile 里只写 shfmt -d bin/opsctl lib test。第 3 课的代码有不少“对齐用的空格”和单行 case 分支(如 -v|--verbose) config::set_flag …; shift ;;),第 3 课 cmd_servers.sh 中 util::in_list … \ 换行后以 || 开头的写法在 binary_next_line = true 下会被保留,而行尾 || 的写法会被移到下一行行首——第一次 shfmt -d 出现较大的 diff 是正常的,审阅后运行一次 -w 并单独提交即可。
printf 'if true; then\n echo hi\n' > bad.sh shfmt bad.sh >/dev/null; echo "rc=$?"
bad.sh:1:1: "if" must end with "fi" rc=1
对比 M1 中 bash -n 报的是“第 3 行 unexpected end of file”,shfmt 直接指出第 1 行的 if 没有闭合。
cd ~/bashlab/opsctl git add -A && git commit -qm "chore: before shfmt" || true
shfmt -f . # 列出识别为 Shell 的文件(注意是否包含子模块,见下) shfmt -d bin/opsctl lib; echo "rc=$?"
shfmt -f . 会递归进入 test/bats 等子模块目录;在 Makefile 中显式列出 bin/opsctl lib test/*.bats,不要格式化第三方代码(或在 .editorconfig 中对 [test/bats/**] 等设 ignore = true)。
shfmt -l -w bin/opsctl lib git diff --stat git diff bin/opsctl | head -n 20
awk 'length > 80 {printf "%s:%d: %d 列\n", FILENAME, FNR, length}' bin/opsctl lib/*.sh
grep -n '`' bin/opsctl lib/*.sh || echo "没有反引号"
ls -l lib/*.sh | awk '{print $1, $NF}' # 库文件不应有 x 权限
grep -c '^main "\$@"$' bin/opsctl # 应为 1
awk length 按字符计(GNU awk 在 UTF-8 locale 下),中文字符在终端中占两列,所以 80 列规则对中文注释只是近似。
git commit -qam "style: shfmt" git rev-parse HEAD >> .git-blame-ignore-revs git config blame.ignoreRevsFile .git-blame-ignore-revs
问题:一个运维团队的合并请求里一半的 diff 是 Tab/空格互换,评审效率极低。做法:一次性提交 .editorconfig + 全仓库 shfmt -w(单独提交并加入 .git-blame-ignore-revs),CI 加 shfmt -d,编辑器装 shfmt 插件保存即格式化。效果:格式争论从评审中消失。
问题:接入 shfmt 后,所有没有 shebang 的 lib/*.sh 都报解析错误,而有 shebang 的入口脚本正常。原因:shfmt 把 .sh 扩展名视为 POSIX。修复:.editorconfig 中 [*.sh] shell_variant = bash。教训:工具的“自动检测”规则要读手册。
问题:一个“临时脚本”三年内长到 1400 行,包含 JSON 解析、并发和重试。做法:团队把 Google 指南的“超过 100 行或控制流复杂就考虑换语言”写进评审清单,新脚本超过阈值时必须在 PR 中说明理由;那个 1400 行的脚本按 M7 的步骤迁移到 Python。
原因:.sh 文件默认按 POSIX 解析(报错文字类似这样,以实际版本为准)。
printf '[*.sh]\nshell_variant = bash\n' >> .editorconfig shfmt -ln bash -d lib/log.sh # 临时验证(注意:带参数时不读 EditorConfig)
原因:① 命令行带了 -i 等参数,EditorConfig 被忽略;② 从 stdin 读取时没有 --filename;③ 节(section)的通配符没有匹配到文件(bin/opsctl 没有扩展名,需要单独写一节)。
shfmt -d bin/opsctl # 不带格式参数 shfmt --filename=bin/opsctl < bin/opsctl | head
原因:本地与 CI 的 shfmt 版本不同(例如 apt 的 3.12.0 与 CI 下载的 3.14.1 对 heredoc 嵌套在命令替换里的缩进处理不同,3.14.1 修复了这类问题)。
修复:本地与 CI 固定同一版本;用 shfmt --version 确认;或本地也用容器 mvdan/shfmt:v3.14.1。
原因:默认不保留对齐用的多余空格。
修复:接受统一格式(推荐),或在 EditorConfig 中设 keep_padding = true(-kp)。
printf '[vendor/**]\nignore = true\n' >> .editorconfig shfmt -l .
shfmt -d bin/opsctl lib test >/dev/null # 格式与语法都检查 # 只关心语法时:for f in bin/opsctl lib/*.sh; do bash -n "$f" || exit 1; done
需要。shfmt 只管排版(缩进、空格、换行位置)。风格指南还规定了 shfmt 无法自动处理的写法:用 [[ ]]、$( )、main 函数、local 与赋值分开、命名约定(pkg::func、常量大写)、错误写 stderr、库文件不可执行、避免 eval、超过 100 行考虑换语言。其中一部分由 ShellCheck 检查(反引号 SC2006、SC2155),其余靠评审清单。三者分工:shfmt(格式)+ ShellCheck(语义)+ 风格指南与评审(约定)。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
shell_variant = bash 一行被高亮;CI 中 shfmt -d 失败显示 diff。@test → 每个测试一个独立进程 → setup → 测试体 → teardown,以及 setup_file/teardown_file 的时机。run($status、$output、${lines[@]}、-N、!、--separate-stderr)与 bats-assert 断言。$BATS_TEST_TMPDIR 隔离文件系统,用“PATH 前置的假命令”替换 curl 等外部依赖并记录调用参数。run cmd | grep、没有 run 时 set -e 中断测试、以 -- 开头的期望字符串。bats-core(Bash Automated Testing System)是一个兼容 TAP(Test Anything Protocol)的 Bash 测试框架。测试文件以 .bats 结尾,每个测试写成 @test "描述" { … };测试体就是普通的 Bash 代码,任何一条命令失败(非零退出)测试就失败——bats 在测试中开启了 set -e(以及 ERR/DEBUG 跟踪,用来报告失败所在的行)。
| 组件 | 作用 | 本课版本 |
|---|---|---|
| bats-core | 测试运行器:发现测试、隔离执行、输出结果(pretty / TAP / JUnit) | 1.14.0(2026-07-21) |
| bats-support | 辅助库:统一的失败信息格式(bats-assert 依赖它,必须先加载) | 0.3.0 |
| bats-assert | 断言:assert_success、assert_failure、assert_output、assert_line、assert_equal、assert_stderr(2.2.0 起)等 | 2.2.4 |
| bats-file(可选) | 文件断言:assert_file_exists 等 | 0.4.0 |
.bats 文件中的 @test "…" { 改写成普通的 Bash 函数,并登记测试列表。setup_file(如果定义了),在其中 export 的变量对该文件所有测试可见;最后运行 teardown_file。整个测试套件还可以有 setup_suite.bash。setup → 测试函数 → teardown。测试里修改的变量、cd、export PATH 都不会泄露到下一个测试。skip(setup/teardown 对 skip 的测试也会运行)。teardown 中命令失败本身不会让测试失败(ERREXIT 在 teardown 中关闭),但 teardown 返回非零会。$BATS_TEST_TMPDIR(文件级 $BATS_FILE_TMPDIR、套件级 $BATS_SUITE_TMPDIR),运行结束后自动删除(--no-tempdir-cleanup 可保留以便排查)。run cmd args… 在子 Shell里执行命令,从不让测试因它失败;结果放进变量:$status(退出码)、$output(stdout 与 stderr 合并)、${lines[@]}(按行的数组,默认去掉空行)。加 --separate-stderr 后 $output 只含 stdout,stderr 进入 $stderr / ${stderr_lines[@]}。run -2 cmd 要求退出码为 2,run ! cmd 要求非零。使用这些标志前要声明 bats_require_minimum_version 1.5.0,否则 bats 会打印 BW02 警告。
因为 run 在子 Shell 中执行,在 run 里调用的函数对变量的修改不会保留;需要检查副作用时,直接调用函数(不用 run),或检查它写下的文件。bats 1.14.0 起,run 中的函数会遵守你脚本里的 set -e(以前被意外屏蔽),这是一个需要注意的行为变化。
运维脚本往往直接操作生产:删文件、改配置、调 API。没有测试,每次重构都是赌博。bats 让你在几秒内验证:用法与退出码约定、参数解析、错误路径(依赖缺失、文件不存在、API 失败重试)、输出格式(下游脚本依赖它)。
脚本通过 PATH 查找外部命令。在测试的 setup 中把 $BATS_TEST_TMPDIR/bin 放到 PATH 最前面,再在里面写一个可执行的假 curl:它把收到的参数追加到一个文件、输出指定内容、返回指定退出码。这样测试既能控制外部依赖的行为(成功、失败、超时),又能断言“被调用了几次、带了什么参数”。这种方法对脚本零侵入,前提是脚本用命令名调用而不是写死 /usr/bin/curl。
| 适合 bats | 不适合 / 另想办法 |
|---|---|
| CLI 契约:用法、退出码、stdout/stderr 分离、输出格式 | 真实云 API 的端到端行为(用预发环境的集成测试) |
| 参数解析与错误路径 | 需要 root 或修改系统的操作(用容器/虚拟机中的测试) |
| 库函数(source 后直接测) | 性能(用 M5 的基准) |
| 重试、退避、超时逻辑(配合替身与可配置的等待时间) | UI 交互(read -p 之类,尽量设计成可非交互) |
| bats-core | shunit2 | ShellSpec | |
|---|---|---|---|
| 风格 | @test 块 + 普通 Bash | xUnit 函数(testXxx) | BDD DSL(Describe/It) |
| 目标 Shell | Bash | POSIX sh 系列 | 多种 POSIX Shell |
| 生态 | 最活跃;support/assert/file 辅助库;Ubuntu/Homebrew 均有包 | 老牌、轻量 | 内置 mock、覆盖率(借助 kcov) |
run cmd | grep foo 会检查 run 的输出”——Bash 先解析管道,run 的输出给了 grep,而 run 本身不产生输出,测试可能假通过;用 run bats_pipe cmd \| grep foo 或先 run 再 assert_output --partial。② “测试里 ! cmd 能断言失败”——! cmd 不会触发 set -e,只有放在最后一行才会影响结果;用 run ! cmd。③ “$output 只有 stdout”——默认是 stdout+stderr 合并。④ “测试之间可以共享 /tmp/test 目录”——并行运行(--jobs)时会互相踩踏;永远用 $BATS_TEST_TMPDIR。选择场景后点击“下一步”。上方是生命周期阶段,左侧是测试文件(当前执行的行高亮),右侧是进程树与 run 捕获的变量,最下面是 bats 的输出。“引入 bug”场景在 util::retry 中制造差一错误(多试一次),观察断言失败后测试体中止、teardown 仍然执行、失败信息的格式;“忘了用 run”场景观察 set -e 如何直接让测试失败。输出格式来自 bats-core 1.14 与 bats-assert 2.2.4 文档,细节为示例。
| 命令 / 函数 | 作用 | 说明 |
|---|---|---|
bats test/ | 运行目录下所有 .bats | 1.14 起找不到测试会报错(--allow-empty-suite 恢复旧行为) |
bats -f 'health' test/ | 按名称正则过滤 | --filter-tags 按标签过滤(# bats test_tags=…) |
bats --tap / -F junit | TAP / JUnit 输出 | --report-formatter junit -o reports/ 同时保留终端输出 |
bats --jobs 4 | 并行 | 需要 GNU parallel |
bats --print-output-on-failure | 失败时自动打印 $output | CI 中推荐 |
bats -x / --trace | 打印测试中执行的命令 | 调试测试本身 |
bats --no-tempdir-cleanup | 保留临时目录 | 排查失败的测试 |
run [-N|!] [--separate-stderr] cmd | 执行并捕获 | 需要 bats_require_minimum_version 1.5.0 |
assert_success / assert_failure [N] | 检查 $status | 失败时打印 status 与 output |
assert_output [-p|-e] 'x' / refute_output | 完全相等 / 包含 / 正则 / 无输出 | 期望值以 - 开头时用 -- 分隔 |
assert_line [--index N] [-p] 'x' | 某一行或任意一行 | 空行会从 lines 中去掉 |
assert_equal actual expected | 两个值相等 | 注意参数顺序:先实际值 |
assert_stderr / refute_stderr | 检查 $stderr | bats-assert ≥ 2.2.0,配合 --separate-stderr |
load 'path' / bats_load_library name | 加载辅助文件 / 按 BATS_LIB_PATH 加载库 | apt 安装的库在 /usr/lib/bats/ |
skip "原因" | 跳过测试 | 可放在 if 中有条件地跳过 |
echo "# msg" >&3 | 在测试中输出调试信息 | 写 fd 3 才会显示在报告中 |
cd ~/bashlab/opsctl
cat > test/test_helper/common.bash <<'EOF'
# test/test_helper/common.bash —— 所有 .bats 共享的 setup 与测试替身
_common_setup() {
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
PROJECT_ROOT=$(cd "${BATS_TEST_DIRNAME}/.." && pwd)
OPSCTL="${PROJECT_ROOT}/bin/opsctl"
# 隔离开发者环境:优先级是 命令行 > 环境变量 OPSCTL_<KEY> > 配置文件 > 默认值,
# 一个遗留的 OPSCTL_ENV / OPSCTL_HEALTH_RETRIES 就能让“没传选项”的测试结果完全不同
local v
for v in $(compgen -v OPSCTL_); do unset "${v}"; done
unset LOG_LEVEL RETRY_MAX_DELAY
export NO_COLOR=1 # 日志不带颜色码,断言更简单
export OPSCTL_DATA_DIR="${BATS_TEST_DIRNAME}/fixtures/data"
STUB_BIN="${BATS_TEST_TMPDIR}/bin"
mkdir -p "${STUB_BIN}"
export PATH="${STUB_BIN}:${PATH}" # 替身目录放在 PATH 最前面
stub sleep 0 # 重试退避不真的等待,同时记录等待时长
}
# stub <命令名> <退出码> [stdout 内容]
# 生成一个假命令:记录参数到 $BATS_TEST_TMPDIR/<命令名>.calls,输出内容并返回退出码
stub() {
local name=$1 rc=$2 out=${3:-}
cat >"${STUB_BIN}/${name}" <<STUB
#!/usr/bin/env bash
printf '%s\n' "\$*" >>"${BATS_TEST_TMPDIR}/${name}.calls"
printf '%s' '${out}'
exit ${rc}
STUB
chmod +x "${STUB_BIN}/${name}"
}
# calls <命令名>:打印替身收到的全部调用(每次一行)
calls() { cat "${BATS_TEST_TMPDIR}/$1.calls" 2>/dev/null || true; }
EOF
heredoc 的结束标记 STUB 不加引号,所以 ${BATS_TEST_TMPDIR}、${out}、${rc} 在生成假命令时就被展开、写死进文件;\$* 被转义,留到假命令运行时才展开。out 不能包含单引号(演示用的简化)。compgen -v OPSCTL_ 列出所有以 OPSCTL_ 开头的变量——测试进程是独立的,unset 不会影响你的终端。为什么连 sleep 也要替换?v0.3 的 cmd::health 通过第 4 课的 util::retry 重试:第 n 次失败后等待 [0, 2n-1] 秒之间的随机时长(指数退避 + 全抖动,上限 RETRY_MAX_DELAY 默认 30);替换后测试瞬间完成,还能断言等待时长没有超出上界。
health::probe 用 curl -sS -o /dev/null -w '%{http_code} %{time_total}' 取得“状态码 耗时”,所以替身要输出形如 200 0.012 的内容;结果只写日志(stderr),stdout 为空。
cat > test/health.bats <<'EOF'
#!/usr/bin/env bats
# test/health.bats —— opsctl health 的行为测试(第 6 课 cmd::health / health::probe 的契约)
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
}
@test "health: 缺少 URL 时为用法错误(2)" {
run "${OPSCTL}" health
assert_failure 2
assert_output --partial 'missing URL'
}
@test "health: 非 http(s) URL 为用法错误(2)" {
run "${OPSCTL}" health ftp://web-prod-1/
assert_failure 2
assert_output --partial 'URL must start with http://'
}
@test "health: 未知选项为用法错误(2)" {
run "${OPSCTL}" health -x http://web-prod-1/healthz
assert_failure 2
}
@test "health: 200 时成功,只调用一次 curl,stdout 为空" {
stub curl 0 '200 0.012'
run --separate-stderr "${OPSCTL}" health http://web-prod-1/healthz
assert_success
refute_output
assert_stderr --partial 'health ok: http://web-prod-1/healthz code=200'
assert_equal "$(calls curl | wc -l)" 1
}
@test "health: 连续失败 4 次后返回 1,退避等待不超过 1、2、4 秒" {
stub curl 7
run "${OPSCTL}" health -r 4 http://web-prod-1/healthz
assert_failure 1
assert_output --partial 'giving up after 4 attempts'
assert_equal "$(calls curl | wc -l)" 4
local i=0 bound=1 s
while read -r s; do # 全抖动:第 n 次等待 ∈ [0, 2^(n-1)]
((++i))
awk -v s="${s}" -v b="${bound}" 'BEGIN { exit !(s >= 0 && s <= b) }' \
|| fail "第 ${i} 次等待 ${s}s 超出上界 ${bound}s"
bound=$((bound * 2))
done < <(calls sleep)
assert_equal "${i}" 3
}
@test "health: 非期望状态码(503)也算失败,OPSCTL_HEALTH_RETRIES 生效" {
stub curl 0 '503 0.010'
OPSCTL_HEALTH_RETRIES=2 run "${OPSCTL}" health http://web-prod-1/healthz
assert_failure 1
assert_output --partial 'code=503'
assert_equal "$(calls curl | wc -l)" 2
}
@test "health: 命令行 -r 优先于 OPSCTL_HEALTH_RETRIES" {
stub curl 7
OPSCTL_HEALTH_RETRIES=5 run "${OPSCTL}" health -r 2 http://web-prod-1/healthz
assert_failure 1
assert_equal "$(calls curl | wc -l)" 2
}
@test "health: -e 指定期望状态码" {
stub curl 0 '204 0.005'
run "${OPSCTL}" health -e 204 http://web-prod-1/healthz
assert_success
}
@test "health: -t 传给 curl 的连接与总超时" {
stub curl 0 '200 0.010'
run "${OPSCTL}" health -t 3 http://web-prod-1/healthz
assert_success
[[ "$(calls curl)" == *'--connect-timeout 3 --max-time 6 -- http://web-prod-1/healthz'* ]]
}
EOF
test/bats/bin/bats test/health.bats
health.bats ✓ health: 缺少 URL 时为用法错误(2) ✓ health: 非 http(s) URL 为用法错误(2) ✓ health: 未知选项为用法错误(2) ✓ health: 200 时成功,只调用一次 curl,stdout 为空 ✓ health: 连续失败 4 次后返回 1,退避等待不超过 1、2、4 秒 ✓ health: 非期望状态码(503)也算失败,OPSCTL_HEALTH_RETRIES 生效 ✓ health: 命令行 -r 优先于 OPSCTL_HEALTH_RETRIES ✓ health: -e 指定期望状态码 ✓ health: -t 传给 curl 的连接与总超时 9 tests, 0 failures
各断言依据的行为都已用同样的替身在本机直接运行重建的 v0.3.0 核对过:退出码 2/1/0、日志 health ok: … code=200、code=503、giving up after 4 attempts、curl 参数 --connect-timeout 3 --max-time 6 -- URL、OPSCTL_HEALTH_RETRIES=2 时 2 次调用、-r 2 压过 OPSCTL_HEALTH_RETRIES=5、三次等待如 0.403、0.949、1.648(随机,但都不超过 1、2、4)。bats 本身没有在编写环境中运行。OPSCTL_HEALTH_RETRIES=2 run …:给 Shell 函数(run 是函数)加前置赋值,Bash 会在函数执行期间临时设置该变量并导出给子进程。
test/bats/bin/bats --tap test/ mkdir -p reports && test/bats/bin/bats --report-formatter junit --output reports test/
1..9 ok 1 health: 缺少 URL 时为用法错误(2) ok 2 health: 非 http(s) URL 为用法错误(2) ok 3 health: 未知选项为用法错误(2) ok 4 health: 200 时成功,只调用一次 curl,stdout 为空 ok 5 health: 连续失败 4 次后返回 1,退避等待不超过 1、2、4 秒 ok 6 health: 非期望状态码(503)也算失败,OPSCTL_HEALTH_RETRIES 生效 ok 7 health: 命令行 -r 优先于 OPSCTL_HEALTH_RETRIES ok 8 health: -e 指定期望状态码 ok 9 health: -t 传给 curl 的连接与总超时
# 错:管道在 run 外面,grep 读到的是空输入,测试可能假通过或假失败
run "${OPSCTL}" servers list | grep -q web-prod-1
# 对:先 run,再对 $output 断言
run "${OPSCTL}" servers list
assert_output --partial web-prod-1
# 对:确实需要管道时(bats ≥ 1.10),注意 \| 必须转义
run bats_pipe "${OPSCTL}" servers list \| grep -c prod
VERSION 与夹具 test/fixtures/data/servers.csv)、第 3 步(子模块),以及“命令”分页第 1、2 节(common.bash、health.bats)。test/opsctl.bats(对应 opsctl::main、servers list 与配置优先级):
cd ~/bashlab/opsctl
cat > test/opsctl.bats <<'EOF'
#!/usr/bin/env bats
# test/opsctl.bats —— 入口、help、servers list 与配置优先级的契约测试
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
}
@test "--help: 输出用法并返回 0" {
run "${OPSCTL}" --help
assert_success
assert_line --index 0 --partial 'ops toolbox for ~/bashlab'
}
@test "无参数: 用法写 stderr,退出码 2" {
run --separate-stderr "${OPSCTL}"
assert_failure 2
refute_output
assert_stderr --partial 'Usage:'
}
@test "-V: 与 VERSION 文件一致" {
run "${OPSCTL}" -V
assert_success
assert_output "opsctl $(<"${PROJECT_ROOT}/VERSION")"
}
@test "未知子命令: 退出码 2,stdout 为空" {
run --separate-stderr "${OPSCTL}" nope
assert_failure 2
refute_output
assert_stderr --partial 'unknown command: nope'
}
@test "每个子命令都有 opsctl-summary,且 help <name> 返回 0" {
local f name
for f in "${PROJECT_ROOT}"/lib/cmd_*.sh; do
name=${f##*/cmd_}
name=${name%.sh}
grep -q '^# opsctl-summary: ' "${f}" || fail "${f##*/} 缺少 # opsctl-summary:"
run "${OPSCTL}" help "${name}"
assert_success
done
}
@test "servers list --env prod -o tsv: 只列出 prod,带引号逗号的字段完整" {
run "${OPSCTL}" servers list --env prod -o tsv
assert_success
assert_equal "${#lines[@]}" 2
assert_line --index 0 $'web-prod-1\tprod\tcanadacentral\t10.0.3.10\tweb'
assert_line --index 1 --partial $'\tdb,primary'
}
@test "servers list --env all: 表格带表头" {
run "${OPSCTL}" servers list --env all
assert_success
assert_line --index 0 --regexp '^NAME +ENV +REGION +IP +ROLE$'
assert_equal "${#lines[@]}" 5
}
@test "servers list --env qa: 用法错误 2" {
run "${OPSCTL}" servers list --env qa
assert_failure 2
assert_output --partial "invalid env 'qa'"
}
@test "servers list --env 缺少参数: 用法错误 2" {
run "${OPSCTL}" servers list --env
assert_failure 2
assert_output --partial "option '--env' requires an argument"
}
@test "优先级:命令行 --env 压过 OPSCTL_ENV,且默认不告警" {
OPSCTL_ENV=dev run --separate-stderr "${OPSCTL}" servers list --env prod -o tsv
assert_success
assert_output --partial 'web-prod-1'
refute_output --partial 'web-dev-1'
refute_stderr
}
@test "优先级:没有 --env 时使用 OPSCTL_ENV;-v 时打印 DEBUG 说明覆盖" {
OPSCTL_ENV=dev run "${OPSCTL}" servers list -o tsv
assert_success
assert_output $'web-dev-1\tdev\tcanadacentral\t10.0.1.10\tweb'
OPSCTL_ENV=dev run --separate-stderr "${OPSCTL}" -v servers list --env prod -o tsv
assert_stderr --partial "flag value 'prod' overrides OPSCTL_ENV=dev"
}
@test "servers list: 数据目录不可读时返回 1" {
OPSCTL_DATA_DIR="${BATS_TEST_TMPDIR}/none" run "${OPSCTL}" servers list
assert_failure 1
assert_output --partial 'cannot read'
}
EOF
test/bats/bin/bats test/opsctl.bats
opsctl.bats ✓ --help: 输出用法并返回 0 ✓ 无参数: 用法写 stderr,退出码 2 ✓ -V: 与 VERSION 文件一致 ✓ 未知子命令: 退出码 2,stdout 为空 ✓ 每个子命令都有 opsctl-summary,且 help <name> 返回 0 ✓ servers list --env prod -o tsv: 只列出 prod,带引号逗号的字段完整 ... 12 tests, 0 failures
优先级两个测试对应第 3 课的规则“命令行 > 环境变量 > 配置文件 > 默认值”:命令行覆盖了不同的环境变量值时,默认日志级别下 stderr 完全为空(refute_stderr),只有 -v 才出现 DEBUG … flag value 'prod' overrides OPSCTL_ENV=dev(本机实测)。summary 测试在重建的 v0.3.0 上通过(8 个 cmd_*.sh 都有 summary,help <name> 都返回 0);它的价值在以后:假如有人新增 lib/cmd_cleanup.sh 却忘了第二行的 # opsctl-summary:,opsctl --help 里这个命令的说明会是空的——这个测试会立刻以 cmd_cleanup.sh 缺少 # opsctl-summary: 失败(综合实验里你会亲手验证)。
test/util.bats(source 后调用,不经过入口):
cat > test/util.bats <<'EOF'
#!/usr/bin/env bats
# test/util.bats —— lib/log.sh 与 lib/util.sh 的单元测试
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
source "${PROJECT_ROOT}/lib/log.sh"
source "${PROJECT_ROOT}/lib/util.sh"
}
@test "util::require_cmd: 缺少命令时以 3 退出并列出缺少的命令" {
run util::require_cmd bash no-such-cmd-xyz
assert_failure 3
assert_output --partial 'missing required command(s): no-such-cmd-xyz'
}
@test "util::csv_split: 带引号的逗号与转义引号" {
local -a f
util::csv_split 'db-01,prod,"web,api","say ""hi""",x' f
assert_equal "${#f[@]}" 5
assert_equal "${f[2]}" 'web,api'
assert_equal "${f[3]}" 'say "hi"'
}
@test "log::info: 写 stderr,不写 stdout,带 [PID]" {
run --separate-stderr log::info hello
assert_success
refute_output
assert_stderr --regexp ' INFO +opsctl\[[0-9]+\]: hello$'
}
EOF
util::csv_split 通过 nameref 写回调用者的数组,所以不能用 run(run 在子 Shell 中执行,数组不会回到测试进程)——直接调用,再对数组断言。日志格式 时间 LEVEL opsctl[PID]: 消息 来自第 4 课的 v0.2 log.sh。
test/logs.bats(第 5 课模块 8 已生成 access.sample.log 与 report.expected.tsv):
cat > test/logs.bats <<'EOF'
#!/usr/bin/env bats
# test/logs.bats —— opsctl logs report 的契约测试(第 5 课 cmd::logs)
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
FIX="${BATS_TEST_DIRNAME}/fixtures"
}
@test "logs report --format tsv 与金标准输出逐字节一致" {
[[ -r ${FIX}/report.expected.tsv ]] || skip "先按第 5 课模块 8 生成金标准文件"
run "${OPSCTL}" logs report --format tsv "${FIX}/access.sample.log"
assert_success
assert_output "$(<"${FIX}/report.expected.tsv")"
}
@test "logs report: 没有有效行时返回 1" {
printf 'garbage line\n' >"${BATS_TEST_TMPDIR}/bad.log"
run "${OPSCTL}" logs report "${BATS_TEST_TMPDIR}/bad.log"
assert_failure 1
assert_output --partial 'no valid log lines'
}
@test "logs report: 文件不可读时返回 1" {
run "${OPSCTL}" logs report "${BATS_TEST_TMPDIR}/nope.log"
assert_failure 1
assert_output --partial 'cannot read log file'
}
@test "logs report --top x: 用法错误 2" {
run "${OPSCTL}" logs report --top x "${FIX}/access.sample.log"
assert_failure 2
assert_output --partial "invalid top 'x'"
}
EOF
test/bats/bin/bats test/
health.bats ✓ health: 缺少 URL 时为用法错误(2) ... logs.bats ✓ logs report --format tsv 与金标准输出逐字节一致 ... opsctl.bats ... util.bats ✓ util::require_cmd: 缺少命令时以 3 退出并列出缺少的命令 ✓ util::csv_split: 带引号的逗号与转义引号 ✓ log::info: 写 stderr,不写 stdout,带 [PID] 28 tests, 0 failures
上面三个错误路径的文字(no valid log lines in … (expected combined log format)、cannot read log file: …、invalid top 'x' (from flag); expected a positive integer)与金标准的生成/比对都在本机对重建的 v0.3.0 实际运行过。金标准测试只断言 tsv(机器格式);text 报表的排版改动不应该让测试失败。
util::retry 里制造一个“差一”错误(多重试一次),重跑:
sed -i 's/(( attempt >= tries ))/(( attempt > tries ))/' lib/util.sh # macOS: sed -i '' test/bats/bin/bats -f '连续失败 4 次' test/health.bats sed -i 's/(( attempt > tries ))/(( attempt >= tries ))/' lib/util.sh # 改回来 git diff --stat lib/util.sh # 应该没有改动
health.bats
✗ health: 连续失败 4 次后返回 1,退避等待不超过 1、2、4 秒
(from function `assert_equal' in file test/test_helper/bats-assert/src/assert_equal.bash, line 40,
in test file test/health.bats, line 38)
`assert_equal "$(calls curl | wc -l)" 4' failed
-- values do not equal --
expected : 4
actual : 5
--
1 test, 1 failure
本机直接运行引入 bug 的版本:curl 被调用 5 次,日志却仍然写着 giving up after 4 attempts——只看日志的人很难发现,而替身的调用计数一眼就能看出来。这也说明测试要断言行为(调用次数),而不只是断言输出文字。
make-data.sh 是确定性的,可以在 setup_file 里为整个文件生成一次:
setup_file() {
[[ -x ${HOME}/bashlab/make-data.sh ]] || skip "没有 ~/bashlab/make-data.sh"
"${HOME}/bashlab/make-data.sh" "${BATS_FILE_TMPDIR}/data" >/dev/null
export FULL_DATA_DIR="${BATS_FILE_TMPDIR}/data" # 目录名必须以 /data 结尾(脚本的保护)
}
@test "完整数据集:prod 6 台" {
OPSCTL_DATA_DIR=${FULL_DATA_DIR} run "${OPSCTL}" servers list --env prod -o tsv
assert_equal "${#lines[@]}" 6
}
不要直接 export OPSCTL_DATA_DIR:_common_setup 会在每个测试开始时把所有 OPSCTL_* 清掉并指回小夹具,所以用另一个变量名传递,再在测试里前置赋值。
test/bats/bin/bats --no-tempdir-cleanup --print-output-on-failure test/health.bats,按输出中的路径查看 curl.calls。问题:有人把健康检查脚本的退避改成“立即重试”,结果服务重启期间 3 次重试在 50ms 内耗尽,部署被误判失败。做法:补一个测试:替身 sleep 记录参数,断言确实发生了 N−1 次等待、且第 n 次不超过 2n−1 秒(带全抖动的退避是随机的,所以断言上界而不是精确值;还可以再断言总等待时长的下界不为 0)。配置:脚本中 sleep 通过 PATH 调用,测试中用 stub sleep 0 替换,既不真的等待又能断言等待时长。
问题:某次修改把一条 info 日志写到了 stdout,下游 opsctl servers list | xargs … 把日志当成主机名去 SSH。做法:契约测试用 run --separate-stderr 并断言 ${#lines[@]} 与每一行内容;log::* 的单元测试断言 refute_output。效果:此类问题在 PR 阶段就被拦截。
问题:多个测试都写 /tmp/opsctl-test,开启 --jobs 4 后随机失败。做法:全部改用 $BATS_TEST_TMPDIR;需要跨测试共享的只读数据放在 setup_file 里生成到 $BATS_FILE_TMPDIR。
原因:没有安装 bats,或克隆仓库时没有拉取子模块。
git submodule update --init --recursive ls test/bats/bin/bats test/test_helper/bats-assert/load.bash
原因:load 的相对路径以测试文件所在目录为基准,而辅助库不在那里;或用 apt 安装的库却按子模块路径加载。
# 子模块布局: load 'test_helper/bats-support/load' # apt 安装(/usr/lib/bats/…): export BATS_LIB_PATH=/usr/lib/bats # 在运行 bats 前设置 bats_load_library bats-support bats_load_library bats-assert
原因:使用了 run -N、run ! 或 --separate-stderr,但没有声明最低版本。
修复:在文件顶部(setup 之外)加 bats_require_minimum_version 1.5.0。
原因:bats-assert 把以 - 开头的参数当作选项解析(报错文字以实际为准)。
assert_output --partial -- '--env 需要一个参数'
原因:没有给 run 加 --separate-stderr,stderr 已经合并进 $output。
修复:run --separate-stderr cmd,然后用 assert_stderr;或者不分离,直接对 $output 断言。
原因:① 脚本用绝对路径 /usr/bin/curl;② 脚本里重设了 PATH;③ Bash 的命令哈希表缓存了旧路径(同一进程中先调用过 curl);④ 替身文件没有可执行权限或 shebang。
type -a curl # 在测试中用 echo "# $(type -a curl)" >&3 打印 hash -r # 清空命令哈希表
opsctl servers list --env dev -o tsv 只输出一行,且第一列是 web-dev-1。@test "servers list --env dev" {
run -0 "${OPSCTL}" servers list --env dev -o tsv
assert_equal "${#lines[@]}" 1
assert_output --regexp '^web-dev-1'$'\t'
}curl 不存在时 opsctl health 以 3 退出(提示:直接测库函数)。@test "require_cmd curl 缺失" {
source "${PROJECT_ROOT}/lib/log.sh"; source "${PROJECT_ROOT}/lib/util.sh"
run util::require_cmd curl-does-not-exist
assert_failure 3
}
# 端到端版本:构造一个只包含 bash/awk/dirname 等必要命令的 PATH(用符号链接),不放 curldeploy 子命令会调用 rsync 和 systemctl restart。如何在不碰真实系统的前提下测试“rsync 失败时不会重启服务,并且回滚”?① 在 setup 中把 $BATS_TEST_TMPDIR/bin 放到 PATH 最前面;② stub rsync 23(模拟部分传输失败)、stub systemctl 0;③ 部署目录、current 符号链接都指向 $BATS_TEST_TMPDIR 下(脚本需要通过变量或配置文件提供这些路径,这正是“可测试性设计”);④ 断言:assert_failure、calls systemctl 为空(assert_equal "$(calls systemctl)" "")、readlink current 仍指向旧版本;⑤ 再写一个 rsync 成功的测试,断言 systemctl 收到了 restart myapp。如果脚本需要 sudo,把 sudo 也做成替身(exec "$@")。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
$(…)、管道和外部命令在循环中代价高(fork + exec + 等待),并能数出一段代码每次迭代产生几个进程。[[ =~ ]]、printf -v、$(<file)、mapfile、read 等内建替代外部命令。time/TIMEFORMAT、EPOCHREALTIME、hyperfine、strace -c -f 量化性能,而不是凭感觉。执行一个内建(printf、[[、read、参数展开、算术)只是解释器里的一次函数调用,微秒级。执行一个外部命令需要:fork()(复制进程)→ 子进程 execve()(加载新程序、动态链接、初始化 locale)→ 父进程 wait()。在 Linux 上这通常是约一毫秒级,在 Windows 的 Git Bash / Cygwin 上(fork 需要模拟)可以达到几十毫秒。命令替换 $(…) 和管道的每一段都至少要 fork 一个子 Shell。
| 写法 | 每次迭代的进程数 | 替代写法(0 进程) |
|---|---|---|
b=$(basename "$f") | 2(子 Shell + basename) | b=${f##*/} |
d=$(dirname "$f") | 2 | d=${f%/*}(注意没有斜杠时的边界) |
ext=$(echo "$f" | sed 's/.*\.//') | 3(子 Shell + echo 子 Shell + sed) | ext=${f##*.} |
up=$(echo "$s" | tr a-z A-Z) | 3 | up=${s^^}(Bash ≥ 4) |
n=$(expr $n + 1) | 2 | ((++n)) |
ts=$(date +%F) | 2 | printf -v ts '%(%F)T' -1(Bash ≥ 4.2) |
c=$(cat file) | 2 | c=$(<file)(1 次子 Shell,无 exec) |
if echo "$s" | grep -q '^v[0-9]' | 2–3 | [[ $s =~ ^v[0-9] ]] |
len=$(echo -n "$s" | wc -c) | 3 | ${#s}(字符数) |
cmd | while read … | 循环在子 Shell 中,变量丢失 | while read … done < <(cmd) 或 shopt -s lastpipe |
处理 1000 行访问日志、每行用 $(echo | cut | cut) 取状态码:约 4000 次 fork/exec。本机(Windows 上的 Git Bash 5.2)实测 75 秒;同样的逻辑改用参数展开只要 0.19 秒;直接一个 awk 只要 0.04 秒。在 Linux 上差距的绝对值会小很多(fork 便宜),但倍数关系依然存在,而且数据量一大就会被放大。
[[ ]]、(( ))、printf -v、read、mapfile)。find … -exec cmd {} +、xargs -0 -n 100,把 N 次调用合并成 N/100 次;需要并行时用 xargs -P 或 GNU parallel。Bash 5.3 新增了在当前 Shell 中执行、不 fork 的命令替换:${ cmd; }(捕获 stdout)与 ${| cmd; }(取 REPLY 的值)。它们能消除函数调用式命令替换的 fork,但只有 5.3+ 支持,用在需要兼容旧版本的脚本里之前要加版本守卫(M6)。
time、hyperfine),再优化热点;优化后用测试(M4)保证结果一致。| 工具 | 测什么 | 优点 | 注意 |
|---|---|---|---|
time(关键字) | 一条管道的 real/user/sys | 内建、可计时函数和管道;TIMEFORMAT 自定义 | 单次测量,波动大 |
/usr/bin/time -v | 外部程序的最大内存、上下文切换 | 资源细节 | 不能计时 Shell 函数 |
EPOCHREALTIME | 脚本内任意两点的耗时 | 无 fork、微秒级(Bash ≥ 5.0) | 值是带小数点的字符串,算术前需去掉小数点 |
| hyperfine | 多次运行的统计(均值 ± 标准差) | 预热、比较多个命令、导出 Markdown/JSON | 测的是整个命令(含 Shell 启动) |
strace -c -f | 系统调用次数(clone/execve) | 直接数出 fork 次数 | 有显著开销,只用于诊断 |
| PS4 带时间戳的 xtrace | 逐行耗时 | 定位慢的那一行(M1) | 开销大,结果偏大 |
[ 比 [[ 快因为更简单”——两者都是内建,差别可以忽略;选 [[ 是为了正确性。② “echo 在命令替换里不 fork”——$(echo x | cut …) 中命令替换本身就要 fork 一个子 Shell,管道的每一段再各 fork 一次。③ “优化就是把一切写成一行”——可读性下降而性能几乎不变;关键是减少每次迭代的进程数。④ “在 set -e 下 ((n++)) 很安全”——当 n 为 0 时 ((n++)) 的值为 0、返回 1,会让脚本退出;计数用 ((++n)) 或 n=$((n + 1))。任务:统计 access.log 中 5xx 响应的行数。选择写法、行数和“每次 fork/exec 的成本”(Linux 约 0.5–1 ms;本机 Git Bash 实测约 18–25 ms),点击“运行”:上方逐行生成进程方块(只画前 30 行),下方计数器累计进程数并估算总耗时。三种写法的真实测量值见“命令”分页。
| 命令 | 作用 | 说明 |
|---|---|---|
time cmd / TIMEFORMAT='%R s' | 计时(关键字,可计时函数与管道) | %R real、%U user、%S sys、%P CPU 百分比 |
hyperfine -w 3 'cmd1' 'cmd2' | 统计比较 | -N 不经过 Shell;--export-markdown |
strace -f -c -e trace=process bash x.sh | 数 clone/execve 次数 | 需要 strace;只用于诊断 |
t0=$EPOCHREALTIME | 微秒时间戳(Bash ≥ 5.0) | 算差值:去掉小数点后做整数运算 |
printf -v var fmt … | 格式化结果直接赋给变量 | 代替 var=$(printf …) |
mapfile -t arr < file | 整文件读入数组 | 代替逐行 arr+=("$(…)");Bash ≥ 4.0 |
[[ $s =~ re ]]; ${BASH_REMATCH[1]} | 正则匹配与捕获 | 代替 echo | grep | sed |
cd ~/bashlab/m7
cp ~/bashlab/data/access.log . 2>/dev/null || \
for i in $(seq 1 1000); do
printf '203.0.113.%d - - [17/Nov/2026:10:00:01 +0000] "GET /api/orders HTTP/1.1" %d 512 "-" "curl/8.12.1"\n' \
$((i % 50)) $((i % 10 == 0 ? 500 : 200))
done > access.log
cat > perf.sh <<'EOF'
slow() { # 每行 4 个进程
local n=0 line code
while IFS= read -r line; do
code=$(echo "$line" | cut -d'"' -f3 | cut -d' ' -f2)
if [ "$code" = 500 ]; then n=$((n + 1)); fi
done < access.log
echo "5xx=$n"
}
fast() { # 0 个进程:参数展开 + [[ ]]
local n=0 line rest code
while IFS= read -r line; do
rest=${line#*\" } # 去掉到第一个 '" '(请求行结束)为止
code=${rest%% *} # 取第一个字段:状态码
[[ ${code} == 5?? ]] && ((++n))
done < access.log
echo "5xx=$n"
}
awkv() { # 整个文件 1 个进程
awk '$9 ~ /^5/ {n++} END {print "5xx=" n+0}' access.log
}
TIMEFORMAT='%R s'
time slow; time fast; time awkv
EOF
bash perf.sh
5xx=100 75.095 s 5xx=100 0.187 s 5xx=100 0.036 s
在 Linux(例如 linuxlab 虚拟机)上,slow 通常在数秒量级,fast 与 awkv 在几十到几百毫秒(示例,以实际为准)——但排序关系不变。第 5 课的 access.log 若格式不同,统计数会不同。
sed -i 's/^time slow; time fast; time awkv$/"${1:-fast}"/' perf.sh # 改为按参数只跑一种
strace -f -c -e trace=clone,clone3,execve bash perf.sh slow 2>&1 | tail -n 6
hyperfine -w 2 'bash perf.sh fast' 'bash perf.sh awkv'
% time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- ... 2001 execve ... 4000 clone Benchmark 1: bash perf.sh fast Time (mean ± σ): 48.3 ms ± 1.2 ms [User: 41.0 ms, System: 6.9 ms] Benchmark 2: bash perf.sh awkv Time (mean ± σ): 4.1 ms ± 0.3 ms Summary bash perf.sh awkv ran 11.78 ± 0.94 times faster than bash perf.sh fast
现代 glibc 的 fork 走 clone/clone3 系统调用,所以要同时追踪它们。具体次数会因 Bash 对“最后一段管道直接 exec”的优化而略少于理论值。
t0=$EPOCHREALTIME
fast >/dev/null
t1=$EPOCHREALTIME
echo "elapsed: $(( (${t1/./} - ${t0/./}) / 1000 )) ms"
elapsed: 181 ms
${t1/./} 去掉小数点,把“秒.微秒”变成整数微秒(两者小数位数相同,都是 6 位)。小数点在某些 locale 下可能是逗号,生产代码可用 ${t1//[!0-9]/}。
f=/var/log/nginx/access.log.1.gz
echo "${f##*/}" "${f%/*}" "${f##*.}" "${f%.gz}" # basename / dirname / 扩展名 / 去后缀
s="Hello World"; echo "${s^^}" "${s,,}" "${#s}" "${s// /_}" # 大小写 / 长度 / 替换
printf -v today '%(%F)T' -1; echo "$today" # 不 fork date
[[ "v1.2.3" =~ ^v([0-9]+)\.([0-9]+) ]] && echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}"
mapfile -t hosts < <(cut -d, -f1 ~/bashlab/data/servers.csv); echo "${#hosts[@]} 行"
cd ~/bashlab/opsctl TIMEFORMAT='%R s' time bin/opsctl logs report ~/bashlab/data/access.log > /tmp/report-before.txt
如果你的第 5 课 logs report 已经用 awk 实现,基线就已经很快——那就用上面的 perf.sh 做这个实验。
OPSCTL_TRACE=/tmp/report.trace bin/opsctl logs report ~/bashlab/data/access.log >/dev/null
awk '{print $3}' /tmp/report.trace | sort | uniq -c | sort -rn | head -5 # 第 3 列是 文件:行号:函数strace -f -c -e trace=clone,clone3,execve bin/opsctl logs report ~/bashlab/data/access.log >/dev/null。目标:execve 次数与输入行数无关。$(…)、echo | cut、date 换成参数展开、[[ =~ ]]、printf -v;或把整个循环替换成一个 awk 程序。time bin/opsctl logs report ~/bashlab/data/access.log > /tmp/report-after.txt diff -u /tmp/report-before.txt /tmp/report-after.txt && echo "输出一致"
把这个对拍写成一个 bats 测试(固定的夹具日志 + 期望输出文件),以后任何“优化”都不会悄悄改变报表。
问题:每小时运行的计费脚本逐行读取 200 万行日志,每行调用 $(echo $line | awk '{print $7}') 和 $(date -d …),运行时间超过一小时,任务开始重叠。做法:整个解析改为一个 awk 程序(时间转换用 GNU awk 的 mktime),Bash 只负责参数、锁和上传。效果:40 分钟 → 20 秒。限制:mktime 是 gawk 扩展,在 mawk/BusyBox awk 上不可用(M6)。
问题:同一套 bats 测试,Linux CI 30 秒,开发者的 Git Bash 上 8 分钟。原因:Windows 上 fork 需要模拟,成本高一个数量级。做法:减少测试中的命令替换;推荐开发者在 WSL2 或容器中运行测试(docker run --rm -v "$PWD":/code bats/bats:1.14.0 test)。
问题:清理脚本对 30 万个文件逐个执行 rm。做法:find "$dir" -type f -mtime +30 -delete(无需外部 rm);需要别的命令时用 -exec cmd {} +。效果:30 万次 exec → 0 次(-delete)或几百次(+)。
原因:算术命令 (( expr )) 在表达式值为 0 时返回 1。n++ 的值是递增前的 n,第一次为 0。
((++n)) # 值为递增后的 n(≥ 1),返回 0 n=$((n + 1)) # 赋值语句,总是返回 0
原因:cmd | while read … 的循环在子 Shell 中执行(第 2 课)。
while IFS= read -r line; do ((++n)); done < <(cmd) # 进程替换 # 或:shopt -s lastpipe(仅在作业控制关闭时生效,即脚本中)
原因:进程数达到上限(ulimit -u 或 cgroup 的 pids.max),通常是循环里无节制地后台启动 &,或 fork 太多。
ulimit -u; cat /sys/fs/cgroup/$(awk -F: '$1=="0"{print $3}' /proc/self/cgroup)/pids.max 2>/dev/null
xargs -P 8 -n 1 cmd < list.txt # 用固定的并发度代替无限的 &原因:用的是外部 /usr/bin/printf(例如 env printf、xargs printf),或在 Bash < 4.2(如 macOS 自带 3.2)上运行。%(…)T 只在 Bash 内建 printf 中可用。
修复:确认在 Bash ≥ 4.2 中以内建方式调用;需要兼容 3.2 时退回 date(并接受 fork 成本)。
/srv/app/releases/2026-11-17_1200.tar.gz 拆成目录、文件名、去掉 .tar.gz 的版本号。p=/srv/app/releases/2026-11-17_1200.tar.gz
dir=${p%/*}; file=${p##*/}; ver=${file%.tar.gz}
printf '%s\n' "$dir" "$file" "$ver"basename 与参数展开在 300 次循环中的耗时。f=/var/log/nginx/access.log; TIMEFORMAT='%R s'
time for i in {1..300}; do b=$(basename "$f"); done
time for i in {1..300}; do b=${f##*/}; done
# 本机 Git Bash 实测:7.394 s 对 0.002 sssh host uptime,串行要跑 6 小时。同事建议“把 ssh 换成内建就快了”。你怎么分析?这里的瓶颈是网络往返与远端执行(I/O 等待),不是本机 fork 成本——ssh 无法用内建替代。正确方向:① 并行:xargs -P 50 -I{} ssh -o ConnectTimeout=5 -o BatchMode=yes {} uptime 或 GNU parallel,配合超时;② 复用连接(ControlMaster);③ 更进一步,这已经是“大规模远程执行”,应该使用 Ansible(forks、清单、结果汇总)或专门的监控系统采集负载(M7 的“换工具”信号)。
未找到经核实、专门讲 Bash 性能优化(内建替代外部命令、hyperfine)的英文视频,请以下方分镜脚本和官方文档为准。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
$(echo | cut | cut),每次循环屏幕上冒出四个进程方块,计数器飞速上涨。/bin/sh)、Bash 的 POSIX 模式、BusyBox ash、macOS 自带 Bash 3.2。checkbashisms、shellcheck -s sh、dash -n 和容器(bash:3.2、busybox:1.37)验证可移植性。| 系统 | /bin/sh 实际是 | bash | 说明 |
|---|---|---|---|
| Ubuntu 26.04 / Debian 13 | dash 0.5.12 | 5.3(Ubuntu) | dash 启动快、严格接近 POSIX;系统脚本(如 init 脚本、maintainer scripts)用 sh |
| RHEL / Fedora / Rocky | bash(以 sh 名称启动时进入 POSIX 模式) | 5.x | “在 CentOS 上能跑”不代表 POSIX 兼容 |
| Alpine、多数精简容器镜像 | BusyBox ash | 默认没有(需 apk add bash) | 官方 bash:* 镜像也基于 Alpine:用户空间工具是 BusyBox |
| macOS | 由系统 Bash 3.2 以 POSIX 模式提供(可切换为 dash) | 3.2.57(2007 年的版本,因 GPLv3 许可不再升级);默认交互 Shell 自 Catalina 起是 zsh | Homebrew 安装的新 Bash 在 /opt/homebrew/bin/bash |
| Git for Windows | bash(MSYS2) | 5.2.x | 本课实测环境之一 |
| Bash 写法 | dash 的反应(实测) | POSIX 写法 |
|---|---|---|
[[ $a == b* ]] | [[: not found | case $a in b*) … ;; esac |
arr=(a b) | Syntax error: "(" unexpected | set -- a b(位置参数)或换行分隔的字符串 |
function f { … } | Syntax error: "}" unexpected | f() { … } |
source file | source: not found | . ./file |
echo -e "a\tb" | 输出 -e a<Tab>b | printf 'a\tb\n' |
${x^^}、${x:1:2}、${x/l/L} | Bad substitution | tr、cut、sed,或 ${x#…}/${x%…} |
$((2**10)) | arithmetic expression: expecting primary | 循环相乘,或 awk |
cat <<< hi | Syntax error: redirection unexpected | printf '%s\n' hi | cat |
cmd &> f | 静默地解析成 cmd & + > f:后台运行并清空 f | cmd >f 2>&1 |
echo {1..3} / $RANDOM | 原样输出 {1..3} / 空字符串 | seq 1 3 / awk 'BEGIN{srand();print int(rand()*32768)}' |
set -o pipefail | set: Illegal option -o pipefail(dash 0.5.12) | POSIX.1-2024 已纳入 pipefail,dash 0.5.13 实现了它;旧系统上需要拆开管道检查 |
local v=1 | 正常(dash、ash 都支持) | 严格 POSIX 未定义 local,但实际几乎所有 sh 都支持 |
| 特性 | 引入版本 | 3.2 上的表现 |
|---|---|---|
关联数组 declare -A | 4.0 | declare: -A: invalid option |
mapfile / readarray | 4.0 | mapfile: command not found |
${x,,} / ${x^^} | 4.0 | bad substitution |
|&、&>>、globstar(**)、coproc、;&/;;&、$BASHPID | 4.0 | 语法错误或无效 |
{fd}>file 自动分配 fd、BASH_XTRACEFD | 4.1 | 无效 |
printf '%(fmt)T'、[[ -v var ]]、lastpipe | 4.2 | 无效 |
declare -n(nameref)、wait -n、负数下标 ${a[-1]} | 4.3 | 无效 |
${x@Q}、local -、inherit_errexit;set -u 下 "${empty[@]}" 不再报 unbound | 4.4 | 3.2 上空数组 + set -u 直接报错 |
EPOCHSECONDS / EPOCHREALTIME | 5.0 | 空 |
${ cmd; }、${| cmd; }、GLOBSORT | 5.3 | 语法错误 / 无效 |
这就是 opsctl 入口要求 Bash ≥ 4.4 的原因:lib/log.sh 用了 declare -gA 与 printf %(…)T(4.2),util::csv_split 与 config::get 用了 nameref local -n(4.3),第 4 课的 v0.2 入口又加了 shopt -s inherit_errexit(4.4)并依赖 4.4 起 set -u 下安全的空数组。它的守卫分两条语句写(第 4 课入口原文):
if [ -z "${BASH_VERSION-}" ]; then echo "opsctl: please run with bash, not sh" >&2; exit 3; fi
if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 4) )); then
echo "opsctl: bash >= 4.4 required (found $BASH_VERSION); on macOS: brew install bash" >&2
exit 3
fi
第一条只用 POSIX 语法,dash 执行到它就退出,根本不会去解析下一行的 (( ))(dash 逐条读取、解析、执行);第二条只会在 bash 中运行,3.2 也能解析 (( ))。原则:守卫本身必须能被它要拒绝的那些 Shell 解析,否则旧 Shell 在守卫执行前就会报出难懂的语法错误。v0.2 起守卫之后紧跟着 set -Eeuo pipefail 与 shopt -s inherit_errexit——它们必须放在守卫之后,旧 Bash 才能先看到清楚的提示。
BusyBox 把 ash 和上百个精简工具编进一个二进制。ash 支持部分 bash 扩展(取决于编译选项,例如 [[ ]] 的部分功能、${x//a/b}、${x:1:2}、source、<<<),但没有数组。更常见的坑在工具上:BusyBox 的 sed、grep、date、find、awk 选项比 GNU 少(例如没有 date -d '2 days ago' 的完整解析、没有 gawk 的 mktime/strftime 之外的扩展)。ShellCheck 0.11.0 新增 SC2330,专门警告在 BusyBox 的 [[ ]] 中使用不支持的通配匹配。
| 路线 A:POSIX sh | 路线 B:明确要求 Bash ≥ X | |
|---|---|---|
| shebang | #!/bin/sh | #!/usr/bin/env bash |
| 适用 | 容器 entrypoint、安装脚本(curl | sh)、嵌入式、initramfs、Debian 包维护脚本 | 运维工具、CI 脚本、开发者工具(如 opsctl) |
| 检查 | shellcheck -s sh、checkbashisms、在 dash 与 busybox 中跑测试 | 版本守卫 + 在最低版本(如 bash:4.4 镜像)跑测试 |
| 代价 | 没有数组、[[ ]]、local 以外的便利 | macOS 用户需安装新 Bash |
#!/bin/bash 了,所以 sh script.sh 运行也没问题”——显式用 sh 调用会忽略 shebang,脚本由 dash 解释。② “#!/bin/sh 在我的 Fedora 上测过了”——那里的 sh 是 bash,大部分 bashism 照样能跑,换到 Debian 就坏。③ “#!/bin/bash 最可移植”——NixOS、部分 BSD 上 /bin/bash 不存在,macOS 上它是 3.2;#!/usr/bin/env bash 会使用 PATH 中第一个 bash。④ “可移植性只关乎 Shell”——sed -i、date -d、readlink -f、grep -P、find -printf 在 GNU、BSD(macOS)、BusyBox 之间差异更大;Ubuntu 26.04 默认的 Rust 版 coreutils 个别选项与报错文字也与 GNU 不同。点击任意单元格,查看该特性在该 Shell 中的表现和推荐的替代写法。标“实测”的 dash 结果来自本机(Git for Windows 自带 dash)的真实运行,Bash 3.2 的结果依据 Bash 的 CHANGES/NEWS 中各特性的引入版本,BusyBox 列取决于编译选项(Debian/Ubuntu 与官方 busybox 镜像默认开启 bash 兼容扩展),请用容器自行验证。
(选择单元格后显示示例与替代写法)
| 命令 | 作用 | 说明 |
|---|---|---|
checkbashisms script.sh | 检查 #!/bin/sh 脚本中的 bashism | 来自 Debian devscripts;-x 额外检查 POSIX 未定义但常见的扩展;-f 强制检查非 sh shebang 的文件 |
shellcheck -s sh script | 按 POSIX sh 方言检查 | 报告 SC3xxx;-s dash、-s busybox 针对具体实现 |
dash -n script / bash --posix -n | 用目标 Shell 解析 | 只检查语法 |
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash x.sh | 在 Bash 3.2 上运行 | 模拟 macOS 自带 Bash(用户空间仍是 BusyBox) |
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh x.sh | 在 BusyBox ash 上运行 | 工具也全是 BusyBox 版 |
echo "$BASH_VERSION" "${BASH_VERSINFO[0]}" | 运行时版本 | 非 bash 时为空 |
ls -l /bin/sh、readlink -f /bin/sh | 查看 /bin/sh 指向 | Ubuntu:/bin/sh -> dash |
for s in 'echo -e "a\tb"' 'source /dev/null && echo ok' 'x=abc; echo ${x^^}' 'cat <<< hi' \
'arr=(a b)' 'set -o pipefail && echo pf' 'f(){ local v=1; echo $v; }; f'; do
printf '%-34s => ' "$s"; dash -c "$s" 2>&1 | tr '\n' ' '; echo
done
echo -e "a\tb" => -e a b
source /dev/null && echo ok => dash: 1: source: not found
x=abc; echo ${x^^} => dash: 1: Bad substitution
cat <<< hi => dash: 1: Syntax error: redirection unexpected
arr=(a b) => dash: 1: Syntax error: "(" unexpected
set -o pipefail && echo pf => dash: 1: set: Illegal option -o pipefail
f(){ local v=1; echo $v; }; f => 1
cd ~/bashlab/m7 dash -c 'echo ok &> o.txt; sleep 0.2; echo "[$(cat o.txt)]"'
ok []
echo ok & 在后台运行、输出到终端,> o.txt 作为一个单独的空命令把文件清空。没有任何报错——这就是 bashism 最可怕的地方。
cat > posix-demo.sh <<'EOF' #!/bin/sh name=world if [[ $name == w* ]]; then echo -e "hi\t$name"; fi source ./env.sh files=(a b) EOF checkbashisms posix-demo.sh shellcheck -f gcc posix-demo.sh
possible bashism in posix-demo.sh line 3 (alternative test command ([[ foo ]] should be [ foo ])): if [[ $name == w* ]]; then echo -e "hi\t$name"; fi possible bashism in posix-demo.sh line 3 (echo -e): ... possible bashism in posix-demo.sh line 4 (should be '.', not 'source'): source ./env.sh posix-demo.sh:3:4: warning: In POSIX sh, [[ ]] is undefined. [SC3010] posix-demo.sh:3:28: warning: In POSIX sh, echo flags are undefined. [SC3037] posix-demo.sh:4:1: warning: In POSIX sh, 'source' in place of '.' is undefined. [SC3046] posix-demo.sh:5:7: warning: In POSIX sh, arrays are undefined. [SC3030]
cat > posix-ok.sh <<'EOF' #!/bin/sh name=world case $name in w*) printf 'hi\t%s\n' "$name" ;; esac . ./env.sh 2>/dev/null || : set -- a b # 用位置参数代替数组 for f in "$@"; do printf '%s\n' "$f"; done EOF shellcheck -s sh posix-ok.sh && dash posix-ok.sh
cd ~/bashlab/opsctl sh bin/opsctl help; echo "rc=$?" # Ubuntu 上 sh 是 dash
opsctl: please run with bash, not sh rc=3
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash bin/opsctl help; echo "rc=$?"
opsctl: bash >= 4.4 required (found 3.2.57(1)-release); on macOS: brew install bash rc=3
如果删掉守卫再试,3.2 会先在 shopt -s inherit_errexit(invalid shell option name)、再在 lib/log.sh 的 declare -gA 处报出 declare: -g: invalid option 之类难以理解的错误——守卫的价值就在这里。
docker run --rm -v "$PWD":/code -w /code bash:4.4 bash test/bats/bin/bats test/ docker run --rm -v "$PWD":/code -w /code bash:5.3 bash test/bats/bin/bats test/
bash:4.4(4.4.23)、bash:5.3 镜像标签已于 2026-11-17 在 Docker Hub 核实存在。镜像基于 Alpine:如果测试或 opsctl 依赖 GNU 工具的特定选项(例如第 4 课 util::lock 用的 flock、第 6 课 backup 的 sha256sum、find -printf),在这里就会暴露——这也是一种有价值的可移植性测试。
cat > install.sh <<'EOF'
#!/bin/sh
# install.sh —— 把 opsctl 安装到 PREFIX(默认 ~/.local);POSIX sh,可在 dash/ash 中运行
set -eu
PREFIX=${PREFIX:-$HOME/.local}
src=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$PREFIX/lib/opsctl" "$PREFIX/bin"
cp -R "$src/bin" "$src/lib" "$src/VERSION" "$PREFIX/lib/opsctl/"
ln -sf "$PREFIX/lib/opsctl/bin/opsctl" "$PREFIX/bin/opsctl"
printf 'installed opsctl %s to %s\n' "$(cat "$src/VERSION")" "$PREFIX"
EOF
chmod +x install.sh
shellcheck -s sh install.sh && checkbashisms install.sh && echo "POSIX OK"
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh -c 'PREFIX=/tmp/p sh install.sh && ls -l /tmp/p/bin'
第 3 课的 bin/opsctl 用 readlink -f -- "${BASH_SOURCE[0]}" 先解析符号链接再计算 OPSCTL_HOME,所以经过 ~/.local/bin/opsctl 这样的链接调用也能找到 lib/。readlink -f 在 GNU 与 BusyBox 上可用,macOS 自 12.3 起也支持——这是入口里少数依赖外部工具行为的地方,值得写进 README。
问题:把镜像从 debian:13-slim 换成 alpine 后,容器启动即退出:/entrypoint.sh: line 5: syntax error: unexpected "("。原因:脚本以 #!/bin/sh 开头却用了数组,Alpine 的 sh 是 BusyBox ash(没有数组);Debian 上的 dash 其实也会失败,但之前镜像里的入口是 bash /entrypoint.sh 显式调用的。修复:入口改为纯 POSIX(用 set --),CI 中用 shellcheck -s sh 与 busybox 镜像验证。
问题:脚本用 sed -i '' 's/a/b/' f(BSD 写法),在 GNU sed 上 '' 被当作脚本、真正的脚本被当作文件名。做法:写成两边都接受的形式 sed -i.bak 's/a/b/' f && rm f.bak,或用 perl -pi -e,或要求开发者安装 GNU sed(gsed)。教训:可移植性更多是“工具”的问题,而不只是 Shell。
问题:一个内部 .deb 包的 postinst 用了 [[ ]],在开发者机器(/bin/sh 被改成 bash)上正常,在标准服务器上安装失败。做法:打包流水线加入 checkbashisms debian/*.postinst debian/*.prerm(Debian 的 lintian 也会检查)。
原因:脚本由 dash 执行(sh script 调用或 #!/bin/sh),而脚本用了 bash 语法。
head -1 script.sh; ls -l /bin/sh bash script.sh # 临时:显式用 bash # 根治:shebang 改为 #!/usr/bin/env bash 并加 chmod +x,用 ./script.sh 运行;或把脚本改成 POSIX
原因:在 Bash 3.2(macOS 的 /bin/bash)中使用关联数组。
brew install bash command -v bash # 确认 /opt/homebrew/bin/bash 在 PATH 前面 # 脚本用 #!/usr/bin/env bash,并加版本守卫
原因:Bash < 4.4 中,set -u 下展开空数组 "${arr[@]}" 会报 unbound variable。
"${arr[@]+"${arr[@]}"}" # 兼容旧版本的写法
# 或要求 Bash ≥ 4.4原因:shebang 行以 CRLF 结尾,env 去找名为 bash\r 的程序。
sed -i 's/\r$//' script.sh && git add --renormalize .
原因:date -d 的自由格式解析是 GNU 扩展;macOS 用 date -v-2d,BusyBox 只支持有限格式。
printf -v d '%(%F)T' "$(( EPOCHSECONDS - 2*86400 ))" # Bash ≥ 5.0,不依赖 date 的实现
if [[ $f == *.log ]]; then echo -e "log:\t$f"; fi 改写为 POSIX sh。case $f in *.log) printf 'log:\t%s\n' "$f" ;; esac
if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 5 ]; then
echo "需要 Bash >= 5.0(当前 ${BASH_VERSION:-非 bash})" >&2
exit 3
fi
# dash 中 ${BASH_VERSINFO:-} 为空,|| 短路,带数组下标的那一段根本不会被展开curl -fsSL https://…/install.sh | sh),用户可能在 Ubuntu、Alpine、macOS 上运行。你会怎么设计与验证?① 目标是“最内圈”:#!/bin/sh + 严格 POSIX,不用数组、[[ ]]、echo -e、source、&>;② 工具只用 POSIX 选项(uname、mkdir -p、cp、printf),检测平台用 uname -s/uname -m;下载工具兼容 curl 与 wget;③ 把全部逻辑放进函数,最后一行才调用 main "$@",防止“下载到一半就执行”;④ 验证:shellcheck -s sh、checkbashisms,CI 矩阵在 debian(dash)、alpine/busybox(ash)、macos-latest 上运行;⑤ 提供校验和或签名,并在文档中给出“先下载、审阅、再运行”的替代方式。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
Bash 擅长编排进程:把现成的命令行工具(git、curl、tar、rsync、kubectl、awk、jq)用管道、重定向和退出码粘在一起;启动快、无需安装、在所有 Linux 上都有。只要“主要工作由外部命令完成、Bash 只负责顺序与错误处理”,它就是合适的。
| # | 信号 | 为什么 Bash 不擅长 | 更合适 |
|---|---|---|---|
| 1 | 脚本超过约 100 行,或控制流不直观(Google 风格指南的标准) | 没有模块系统、类型和真正的作用域,维护成本随行数非线性上升 | Python / Go |
| 2 | 需要嵌套数据结构(字典里套列表、对象数组) | 只有一维索引数组与关联数组(且 3.2 没有关联数组),无法嵌套 | Python(dict/list)、Go(struct) |
| 3 | 大量 JSON/YAML 读写、而不只是取一两个字段 | 需要 jq/yq 往返,引用与转义极易出错 | Python、Go;少量取值用 jq 即可 |
| 4 | 浮点运算、日期计算、精确的字符串处理(Unicode、CSV 带引号字段) | 只有整数算术;依赖 bc/date/awk,且实现之间有差异(M6) | Python |
| 5 | 需要细粒度错误处理(区分错误类型、带上下文重试、清理多种资源) | 只有 8 位退出码和 stderr 文本;set -e 例外规则复杂(第 4 课) | Python(异常)、Go(error 值) |
| 6 | 并发且需要共享状态(工作池、限流、汇总结果) | &/wait -n/xargs -P 只适合独立任务 | Go(goroutine、channel)、Python(concurrent.futures / asyncio) |
| 7 | 常驻进程、HTTP 服务、长时间运行的守护程序 | 信号、内存、日志、健康检查都要手工拼 | Go、Python + systemd |
| 8 | 需要在 Windows 原生运行、或分发给不受控的机器 | 依赖 Bash 版本与 GNU/BSD 工具差异 | Go(单个静态二进制) |
| 9 | 处理不可信输入、拼接命令(eval、ssh host "$cmd") | 引号与注入风险高,难以审计 | Python(subprocess.run([...]) 参数列表)、Go(exec.Command) |
| 10 | 性能已经优化到头(M5)仍不够 | 解释执行、每个外部命令都是一次 fork/exec | Go、Python + 合适的库 |
| 11 | “在多台主机上让配置收敛到期望状态” | 脚本是命令式的,难以幂等、难以汇报“改了什么” | Ansible(声明式、幂等、清单、--check/--diff) |
| 12 | “创建/管理云资源的生命周期” | 没有状态、依赖图与计划(plan) | Terraform |
越界的 Bash 脚本不会突然坏掉,而是慢慢变得没人敢改:每次修改都可能触发某个引号、子 Shell 或 set -e 例外的边角情况。迁移成本随时间增长——最便宜的迁移时机就是“第一次出现上表中的信号时”。
opsctl logs report 由 Python 实现,入口的 cmd::logs 改为 exec python3 "${OPSCTL_HOME}/libexec/logs_report.py" "$@"。OPSCTL_IMPL=py)先给一部分用户;稳定后删掉旧实现。argparse/click)或 Go(cobra),Bash 只保留真正的胶水部分(例如安装脚本)。| Python | Go | |
|---|---|---|
| 分发 | 需要解释器与依赖(venv、uv、pipx);系统自带 python3 版本各异 | 单个静态二进制,交叉编译到 Linux/macOS/Windows |
| 开发速度 | 快,标准库覆盖 json、csv、re、pathlib、subprocess、argparse | 中等,类型系统更严格 |
| 并发 | I/O 并发好(asyncio、线程池);CPU 并发受 GIL 影响(3.13+ 有实验性自由线程版本) | goroutine 原生、简单 |
| 适合 | 数据处理、报表、胶水升级版、团队熟悉 Python | 分发给很多机器的 CLI、常驻服务、高并发 |
subprocess.run(..., shell=True) 照样有注入和引号问题;应传参数列表。勾选你的脚本符合的情况,右侧实时给出建议和理由。权重是本课的经验值,不是标准——目的是把“感觉这个脚本有点复杂”变成可以讨论的具体信号。
任务:统计访问日志的状态码分布,输出 状态码 次数,按状态码排序;无法解析的行跳过并在 stderr 报告。
awk '$9 ~ /^[0-9][0-9][0-9]$/ {c[$9]++} END {for (k in c) print k, c[k]}' access.log | sort
mkdir -p ~/bashlab/opsctl/libexec
cat > ~/bashlab/opsctl/libexec/logs_report.py <<'EOF'
#!/usr/bin/env python3
"""logs_report.py —— 统计访问日志的状态码分布(与 awk 版本输出一致)。"""
import re
import sys
from collections import Counter
LINE = re.compile(r'^\S+ \S+ \S+ \[[^\]]+\] "[^"]*" (\d{3}) ')
def main(argv: list[str]) -> int:
if len(argv) != 2:
print("用法: logs_report.py ACCESS_LOG", file=sys.stderr)
return 2
counts: Counter[str] = Counter()
bad = 0
try:
with open(argv[1], encoding="utf-8", errors="replace") as fh:
for line in fh:
m = LINE.match(line)
if m:
counts[m.group(1)] += 1
else:
bad += 1
except FileNotFoundError:
print(f"找不到文件: {argv[1]}", file=sys.stderr)
return 1
for code in sorted(counts):
print(f"{code} {counts[code]}")
if bad:
print(f"跳过 {bad} 行无法解析的记录", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
EOF
chmod +x ~/bashlab/opsctl/libexec/logs_report.py
cd ~/bashlab/m7
python3 ~/bashlab/opsctl/libexec/logs_report.py access.log > py.txt
awk '$9 ~ /^[0-9][0-9][0-9]$/ {c[$9]++} END {for (k in c) print k, c[k]}' access.log | sort > awk.txt
diff -u awk.txt py.txt && echo "输出一致"
python3 ~/bashlab/opsctl/libexec/logs_report.py; echo "rc=$?"
跳过 1 行无法解析的记录 200 900 401 1 500 100 输出一致 用法: logs_report.py ACCESS_LOG rc=2
在 Windows 上直接运行 Python 时 stdout 默认是 CRLF 换行,diff 会报告每一行都不同(本机实测就遇到了);Linux/macOS 上没有这个问题,Windows 上可以用 diff --strip-trailing-cr。这也是一个“跨平台”信号的小例子。
opsctl codes,两种实现共用一个入口第 5 课的 logs report(lib/cmd_logs.sh + lib/logs_report.awk)已经是一个合格的 awk 报表,并有 M4 的金标准测试保护,不必迁移;这里新建一个独立的小子命令 codes(状态码分布)来演示迁移模式——它遵守第 3 课的约定(lib/cmd_codes.sh、cmd::codes、第二行 # opsctl-summary:),并在 v0.2 的严格模式下运行,不会覆盖你已有的任何文件:
cat > ~/bashlab/opsctl/lib/cmd_codes.sh <<'EOF'
# shellcheck shell=bash
# opsctl-summary: HTTP status code distribution of an access log (codes FILE)
# lib/cmd_codes.sh —— 绞杀者模式演示:OPSCTL_IMPL=py 时交给 Python 实现
cmd::codes() {
if [[ ${1-} == -h || ${1-} == --help ]]; then
echo "用法:opsctl codes <access.log>"
return 0
fi
local file=${1-}
[[ -n ${file} ]] || util::usage_error "codes: missing <access.log>"
[[ -r ${file} ]] || util::die "codes: cannot read ${file}" 1
if [[ ${OPSCTL_IMPL:-bash} == py ]]; then
util::require_cmd python3
exec python3 "${OPSCTL_HOME}/libexec/logs_report.py" "${file}"
fi
awk '$9 ~ /^[0-9][0-9][0-9]$/ { c[$9]++ } END { for (k in c) print k, c[k] }' "${file}" | sort
}
EOF
cd ~/bashlab/opsctl
bin/opsctl codes test/fixtures/access.log; echo "rc=$?"
bin/opsctl codes /nope; echo "rc=$?"
200 2 401 1 500 1 rc=0 2026-11-17T09:49:07-0500 ERROR opsctl[1837]: codes: cannot read /nope rc=1
opsctl --help 的命令列表会自动出现 codes(第 3 课的 opsctl::list_commands 扫描 summary 注释)。用 exec 把进程直接替换成 Python:退出码就是 Python 的退出码,不多一层 Bash 进程。
cd ~/bashlab/opsctl cat > test/fixtures/access.log <<'EOF' 203.0.113.7 - - [17/Nov/2026:10:00:01 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1" 203.0.113.8 - - [17/Nov/2026:10:00:02 +0000] "GET /api/orders HTTP/1.1" 500 31 "-" "Mozilla/5.0 (X11; Linux x86_64)" 203.0.113.9 - - [17/Nov/2026:10:00:03 +0000] "POST /login HTTP/1.1" 401 12 "-" "python-requests/2.32" 203.0.113.7 - - [17/Nov/2026:10:00:04 +0000] "GET / HTTP/1.1" 200 512 "-" "curl/8.12.1" EOF
cat > test/codes.bats <<'EOF'
#!/usr/bin/env bats
# test/codes.bats —— codes 子命令的契约测试;bash 与 py 两种实现跑同一组断言
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
}
assert_codes_report() {
run --separate-stderr "${OPSCTL}" codes "${BATS_TEST_DIRNAME}/fixtures/access.log"
assert_success
assert_output "$(printf '200 2\n401 1\n500 1')"
}
@test "codes(bash 实现)" {
OPSCTL_IMPL=bash assert_codes_report
}
@test "codes(python 实现)" {
command -v python3 >/dev/null || skip "没有 python3"
OPSCTL_IMPL=py assert_codes_report
}
@test "codes: 文件不存在时返回 1(两种实现都在入口检查)" {
run "${OPSCTL}" codes /nonexistent.log
assert_failure 1
}
@test "codes: 缺少参数时为用法错误 2" {
run "${OPSCTL}" codes
assert_failure 2
}
@test "完整数据集的对拍:两种实现输出逐字节一致" {
command -v python3 >/dev/null || skip "没有 python3"
local log=${HOME}/bashlab/data/access.log
[[ -r ${log} ]] || skip "没有第 1 课的 access.log"
diff <(OPSCTL_IMPL=bash "${OPSCTL}" codes "${log}") <(OPSCTL_IMPL=py "${OPSCTL}" codes "${log}" 2>/dev/null)
}
EOF
test/bats/bin/bats test/codes.bats
codes.bats ✓ codes(bash 实现) ✓ codes(python 实现) ✓ codes: 文件不存在时返回 1(两种实现都在入口检查) ✓ codes: 缺少参数时为用法错误 2 ✓ 完整数据集的对拍:两种实现输出逐字节一致 5 tests, 0 failures
在本机直接运行(不经过 bats)时,两种实现对夹具的输出都是 200 2、401 1、500 1;唯一的差异是 Windows 上 Python 输出 CRLF——Linux/macOS 上不存在。第 1 课的完整 access.log(611 行,5xx 共 28 行:500×12、502×4、503×12)可以用来做最后一个对拍测试。OPSCTL_IMPL=bash assert_codes_report 是给函数加前置赋值,变量会传给其中 run 启动的 opsctl。
deploy 涉及多主机时,考虑 Ansible)。问题:一个发布脚本解析 YAML 清单、调用 3 个 API、并发上传制品、失败时回滚,长到 1400 行,三年里出了 5 次事故,没人敢改。做法:先写 40 个 bats 契约测试冻结行为;按子命令迁移到 Python(YAML 用 PyYAML、HTTP 用 requests、并发用线程池);入口在 6 周内从“Bash 调 Python”变成“纯 Python + 一个薄的 Bash 安装脚本”。效果:代码量降到 600 行,有单元测试与类型检查,事故归零。
问题:for h in $(cat hosts); do ssh "$h" "sudo sed -i … && systemctl restart …"; done——无法重试失败主机、无法知道谁改了什么、引号层层嵌套。做法:改为 Ansible playbook(lineinfile + handler),获得幂等、--check --diff 预演、失败主机重试文件。详见 Ansible 8 小时。
问题:一个 Bash 工具在 macOS(3.2)、Ubuntu、WSL 上表现各不相同,支持成本很高。做法:用 Go 重写为单个二进制,通过包管理器分发;保留原 bats 测试作为端到端测试(bats 可以测试任何命令行程序)。
原因:换行符(Windows 上的 CRLF)、末尾换行、排序规则(sort 受 locale 影响,Python 的 sorted 按码点)。
diff <(LC_ALL=C sort awk.txt) <(LC_ALL=C sort py.txt) cat -A py.txt | head -3 # 看到 ^M$ 就是 CRLF
原因:目标机器没有 Python 或版本 < 3.9。
修复:入口里用 util::require_cmd python3 给出退出码 3;文档写明最低版本;或者改用 Go 生成静态二进制。
原因:使用了 subprocess.run(f"tar czf {name} …", shell=True)。
subprocess.run(["tar", "czf", name, "-C", src, "."], check=True) # 参数列表,不经过 Shell
原因:Python 未捕获的异常默认退出码为 1,用法错误时 argparse 默认退出码为 2——与 opsctl 约定(3 = 依赖缺失)不完全一致。
修复:在 main() 中捕获并映射异常到约定的退出码;契约测试覆盖每个退出码。
~/bashlab/data/inventory.json 取出所有 prod 主机名——这还算 Bash 的甜区吗?jq -r '.[] | select(.env == "prod") | .name' ~/bashlab/data/inventory.json # 算:一次性取值,jq 完成全部数据处理,Bash 只是胶水。 # 如果需要按区域分组、合并多个 JSON、再生成新的 JSON —— 考虑 Python。
rsync,并在失败时以退出码 1 结束。import subprocess, sys
r = subprocess.run(["rsync", "-a", "--delete", src + "/", dst], check=False)
if r.returncode != 0:
print(f"rsync 失败: {r.returncode}", file=sys.stderr)
sys.exit(1)opsctl report --format json:汇总 50 台主机的健康检查结果(并发)、计算 P95 延迟、输出嵌套 JSON。你会继续用 Bash 吗?不建议。这个需求同时命中多个信号:并发且需要汇总共享结果(#6)、浮点计算 P95(#4)、生成嵌套 JSON(#2、#3)。建议:用 Python 实现 libexec/report.py(concurrent.futures.ThreadPoolExecutor + statistics.quantiles + json.dumps),由 Bash 入口分派;用 bats 写契约测试(用 JSON 夹具和 jq -e 断言结构)。如果 opsctl 未来要分发到大量机器、或要变成常驻服务,再评估 Go。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
lint、fmt、fmt-check、test、check、release 目标,让本地与 CI 执行完全相同的命令。VERSION 文件 + git 标签 + git archive + sha256sum 做可复现的发布,并在 CI 中校验版本一致。对一个运维 CLI 来说,“1.0”是一个承诺:用法、退出码、stdout 格式从此按语义化版本管理(破坏性变化需要升主版本)。兑现这个承诺需要三样东西:契约测试(M4)保证行为不变、质量门禁(M2、M3)保证每次合并的代码都过检查、可复现的发布保证用户拿到的就是被测试过的那个提交。
opsctl/
├── VERSION # 1.0.0(唯一的版本来源)
├── Makefile # lint / fmt / fmt-check / test / check / release
├── justfile # 可选:与 Makefile 等价
├── .editorconfig # shfmt 配置(M3)
├── .shellcheckrc # ShellCheck 配置(M2)
├── .gitattributes # eol=lf;release 时排除 test/ 等
├── .github/
│ ├── workflows/ci.yml # 检查 + 打标签发布
│ └── dependabot.yml # 自动更新被固定的 action SHA
├── bin/opsctl # 入口(可执行,无扩展名)
├── lib/ # log.sh util.sh config.sh cmd_*.sh logs_report.awk(不可执行)
├── libexec/logs_report.py # M7 codes 子命令的 Python 实现(可选)
├── etc/opsctl.conf
├── var/lock/ # util::lock 的锁文件(第 4 课;已在 .gitignore 中忽略 var/)
├── install.sh # POSIX sh 安装脚本(M6)
└── test/
├── bats/ # 子模块 bats-core v1.14.0
├── test_helper/ # 子模块 bats-support、bats-assert + common.bash
├── fixtures/ # data/servers.csv access.log access.sample.log report.expected.tsv
├── smoke.sh mockapi.py # 第 6 课的冒烟测试(保留)
├── flaky.sh # 第 4 课演示 util::retry 用
└── *.bats # opsctl health util logs codes
make check 与 CI 运行的是同一条命令,“本地通过 CI 失败”只剩工具版本这一种原因(再通过固定版本消除)。make check(见 GitLab、Jenkins 课程)。| 对象 | 做法 | 原因 |
|---|---|---|
| 第三方 action | uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 | 标签可以被移动,提交 SHA 不能;注释保留可读的版本号,Dependabot 会同时更新 SHA 与注释 |
| 工具版本 | CI 中按版本号下载 ShellCheck v0.11.0、shfmt v3.14.1;bats 用子模块固定在 v1.14.0 | ubuntu-latest 镜像里的预装版本会变化,新版本可能新增告警 |
| 令牌权限 | permissions: contents: read;只有发布作业 contents: write;persist-credentials: false | 最小权限,防止被篡改的步骤推送代码 |
更严格的做法还会校验下载文件的 SHA-256(把官方发布页的校验和写进工作流)。本课为了简洁没有内置具体校验和,“已知限制”中有说明。
make check)。VERSION 为 1.0.0,更新 CHANGELOG,提交。git tag -a v1.0.0 -m "opsctl 1.0.0" && git push origin v1.0.0。VERSION 与标签一致 → git archive → sha256sum → 创建 GitHub Release 并上传。sha256sum -c 校验,再运行 install.sh。| make | just | |
|---|---|---|
| 预装情况 | 几乎所有类 Unix 系统都有 | 需要安装(1.59.0,2026-10) |
| 语法陷阱 | 配方必须用 Tab 缩进;变量 $(VAR) 与 Shell 的 $$var 区分;每行默认一个独立 Shell | 空格缩进即可;{{var}} 插值;错误信息更友好 |
| 适合 | 需要零依赖、或已有 make 生态 | 纯任务运行器 |
uses: actions/checkout@v7 就算固定了”——那是可移动的标签,不是固定。② “CI 用 apt install shellcheck 最简单”——runner 镜像的仓库版本与本地不同,结果不可复现。③ “发布就是把工作目录打个 tar 包”——工作目录可能有未提交的修改、本地生成的文件;git archive <tag> 只打包标签对应的提交。④ “测试通过就可以打标签”——还要确认 VERSION 与标签一致、工作区干净,Makefile 的 release 目标会检查这两点。选择一种“提交”,点击“推送”,观察 GitHub Actions 的各个步骤依次执行、在哪一步失败、日志里会出现什么、以及本地如何复现。日志内容为示例(格式参考各工具的真实输出)。
配方行必须以 Tab 开头(下面的代码块中就是 Tab;复制时如果编辑器把 Tab 转成了空格,make 会报 missing separator)。
cat > ~/bashlab/opsctl/Makefile <<'EOF'
# Makefile —— opsctl 的质量门禁与发布(本地与 CI 共用)
SHELL := bash
.SHELLFLAGS := -eu -o pipefail -c
.DEFAULT_GOAL := check
VERSION := $(shell cat VERSION)
SH_FILES := bin/opsctl $(wildcard lib/*.sh)
BATS := test/bats/bin/bats
DIST := dist
TARBALL := $(DIST)/opsctl-$(VERSION).tar.gz
.PHONY: check lint fmt fmt-check test release clean version
check: lint fmt-check test
lint:
shellcheck --version | sed -n 2p
shellcheck $(SH_FILES)
fmt:
shfmt -w $(SH_FILES) test/*.bats
fmt-check:
shfmt -d $(SH_FILES) test/*.bats
test:
$(BATS) --print-output-on-failure test/
version:
@echo $(VERSION)
release: check
@git diff --quiet && git diff --cached --quiet || { echo "工作区不干净" >&2; exit 1; }
@git rev-parse -q --verify "refs/tags/v$(VERSION)" >/dev/null || { echo "缺少标签 v$(VERSION)" >&2; exit 1; }
mkdir -p $(DIST)
git archive --format=tar.gz --prefix=opsctl-$(VERSION)/ -o $(TARBALL) v$(VERSION)
cd $(DIST) && sha256sum opsctl-$(VERSION).tar.gz > opsctl-$(VERSION).tar.gz.sha256
@echo "已生成 $(TARBALL)"
clean:
rm -rf -- $(DIST) reports
EOF
cd ~/bashlab/opsctl && make -n check | head
macOS 没有 sha256sum 时用 shasum -a 256;GNU make 3.82+ 才支持 .SHELLFLAGS(macOS 自带的 make 3.81 不支持,可 brew install make 后用 gmake)。
cat > ~/bashlab/opsctl/justfile <<'EOF'
# justfile —— 与 Makefile 等价的任务定义(just 1.59.0)
set shell := ["bash", "-euo", "pipefail", "-c"]
version := `cat VERSION`
sh_files := "bin/opsctl lib/*.sh"
default: check
check: lint fmt-check test
lint:
shellcheck {{sh_files}}
fmt:
shfmt -w {{sh_files}} test/*.bats
fmt-check:
shfmt -d {{sh_files}} test/*.bats
test:
test/bats/bin/bats --print-output-on-failure test/
release: check
mkdir -p dist
git archive --format=tar.gz --prefix=opsctl-{{version}}/ -o dist/opsctl-{{version}}.tar.gz v{{version}}
cd dist && sha256sum opsctl-{{version}}.tar.gz > opsctl-{{version}}.tar.gz.sha256
EOF
mkdir -p ~/bashlab/opsctl/.github/workflows
cat > ~/bashlab/opsctl/.github/workflows/ci.yml <<'EOF'
name: ci
on:
push:
branches: [main]
tags: ['v*']
pull_request:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-24.04
timeout-minutes: 10
env:
SHELLCHECK_VERSION: v0.11.0
SHFMT_VERSION: v3.14.1
steps:
- name: Checkout(含 bats 子模块)
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
submodules: recursive
persist-credentials: false
- name: 安装固定版本的 ShellCheck 与 shfmt
run: |
set -euo pipefail
mkdir -p "$HOME/.local/bin"
curl -fsSL "https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION}/shellcheck-${SHELLCHECK_VERSION}.linux.x86_64.tar.xz" \
| tar -xJ -C "$RUNNER_TEMP"
install -m 0755 "$RUNNER_TEMP/shellcheck-${SHELLCHECK_VERSION}/shellcheck" "$HOME/.local/bin/shellcheck"
curl -fsSLo "$HOME/.local/bin/shfmt" \
"https://github.com/mvdan/sh/releases/download/${SHFMT_VERSION}/shfmt_${SHFMT_VERSION}_linux_amd64"
chmod +x "$HOME/.local/bin/shfmt"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: 工具版本
run: |
bash --version | head -n1
shellcheck --version
shfmt --version
test/bats/bin/bats --version
- name: ShellCheck
run: make lint
- name: shfmt
run: make fmt-check
- name: bats
run: make test
release:
needs: check
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: 构建 tarball 与校验和
run: |
set -euo pipefail
v=$(<VERSION)
if [[ "v${v}" != "${GITHUB_REF_NAME}" ]]; then
echo "::error::VERSION (${v}) 与标签 (${GITHUB_REF_NAME}) 不一致"
exit 1
fi
mkdir -p dist
git archive --format=tar.gz --prefix="opsctl-${v}/" -o "dist/opsctl-${v}.tar.gz" "${GITHUB_REF_NAME}"
(cd dist && sha256sum "opsctl-${v}.tar.gz" > "opsctl-${v}.tar.gz.sha256")
- name: 创建 GitHub Release
env:
GH_TOKEN: ${{ github.token }}
run: gh release create "${GITHUB_REF_NAME}" dist/* --title "opsctl ${GITHUB_REF_NAME}" --generate-notes
EOF
要点:① actions/checkout 固定到 v7.0.1 的提交 SHA(2026-11-17 通过 GitHub API 核实 refs/tags/v7.0.1 → 3d3c42e5…);② ShellCheck/shfmt 的下载地址与文件名按 v0.11.0、v3.14.1 发布页的资产名核实;③ runner 选 ubuntu-24.04 而不是 ubuntu-latest,避免镜像升级带来的变化(自带 Bash 5.2,这正好也测试了“非 5.3”的环境);④ gh CLI 在 GitHub 托管 runner 上预装。Actions 语法细节见 GitHub 8 小时。
cat > ~/bashlab/opsctl/.github/dependabot.yml <<'EOF'
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: gitsubmodule
directory: /
schedule:
interval: monthly
EOF
cat > ~/bashlab/opsctl/.gitattributes <<'EOF'
* text=auto eol=lf
/test export-ignore
/.github export-ignore
/.editorconfig export-ignore
/.shellcheckrc export-ignore
/justfile export-ignore
EOF
export-ignore 让 git archive 打包时排除测试和 CI 文件,发布物只包含运行所需的内容。
.shellcheckrc、M3 的 .editorconfig、M4 的测试):
cd ~/bashlab/opsctl make check
shellcheck --version | sed -n 2p version: 0.11.0 shellcheck bin/opsctl lib/cmd_backup.sh lib/cmd_codes.sh lib/cmd_config.sh lib/cmd_deploy.sh lib/cmd_doctor.sh lib/cmd_export.sh lib/cmd_health.sh lib/cmd_logs.sh lib/cmd_servers.sh lib/config.sh lib/log.sh lib/util.sh shfmt -d bin/opsctl lib/cmd_backup.sh lib/cmd_codes.sh lib/cmd_config.sh lib/cmd_deploy.sh lib/cmd_doctor.sh lib/cmd_export.sh lib/cmd_health.sh lib/cmd_logs.sh lib/cmd_servers.sh lib/config.sh lib/log.sh lib/util.sh test/codes.bats test/health.bats test/logs.bats test/opsctl.bats test/util.bats test/bats/bin/bats --print-output-on-failure test/ health.bats ✓ health: 缺少 URL 时为用法错误(2) ... 33 tests, 0 failures
如果 fmt-check 失败,运行 make fmt 后单独提交;第 4–6 课的 cmd_export.sh、cmd_doctor.sh、cmd_logs.sh、cmd_backup.sh、cmd_deploy.sh 也会被 ShellCheck 与 shfmt 检查,并被 M4 的“每个子命令都有 opsctl-summary”测试覆盖——这正是 v1.0 的意义。CI 中还可以加一步运行第 6 课的 test/smoke.sh(需要 python3 起 mock API)作为端到端冒烟测试。测试数 33 = health 9 + opsctl 12 + util 3 + logs 4 + codes 5(codes 来自 M7)。注意 SH_FILES 只匹配 lib/*.sh,第 5 课的 lib/logs_report.awk 不归 ShellCheck/shfmt 管,它由 logs.bats 的金标准测试保护。
echo 1.0.0 > VERSION bin/opsctl --version git add -A git commit -qm "release: opsctl 1.0.0" git tag -a v1.0.0 -m "opsctl 1.0.0"
make release ls -l dist/ (cd dist && sha256sum -c opsctl-1.0.0.tar.gz.sha256) tar -tzf dist/opsctl-1.0.0.tar.gz | head
opsctl-1.0.0.tar.gz: OK opsctl-1.0.0/ opsctl-1.0.0/.gitattributes opsctl-1.0.0/Makefile opsctl-1.0.0/VERSION opsctl-1.0.0/bin/ opsctl-1.0.0/bin/opsctl opsctl-1.0.0/etc/ ...
rm -rf ~/bashlab/m7/install-test && mkdir -p ~/bashlab/m7/install-test tar -xzf dist/opsctl-1.0.0.tar.gz -C ~/bashlab/m7/install-test ~/bashlab/m7/install-test/opsctl-1.0.0/bin/opsctl --version
opsctl 1.0.0
git remote add origin git@github.com:<你的账号>/opsctl.git # 首次 git push -u origin main git push origin v1.0.0 gh run list --limit 3 gh run watch # 交互式选择并实时查看 gh release view v1.0.0
问题:2025 年 3 月,被广泛使用的第三方 action tj-actions/changed-files 遭到入侵,攻击者把多个版本标签指向了恶意提交,使用 @v45 这类标签的工作流在日志中泄露了密钥(CVE-2025-30066)。做法:所有第三方 action 固定到提交 SHA,并用 Dependabot 审阅升级;工作流默认 contents: read。教训:标签是可变的引用,SHA 才是不可变的。
问题:开发者本地 ShellCheck 0.9 零告警,CI 的 runner 镜像升级到 0.11 后出现 SC2329(函数从未被调用)而失败。做法:CI 与本地都固定 v0.11.0;升级 ShellCheck 作为一个单独的 PR,修复新告警后合并。
问题:手工 tar czf opsctl.tgz . 把开发者的 etc/opsctl.conf(含内部地址)和 .git 目录打进了发布包。做法:只用 git archive <tag>,配合 .gitattributes 的 export-ignore;发布在 CI 中完成,开发者机器不产生发布物。
从“哪一步失败”开始,逐步缩小范围;每个结论都给出本地复现命令与修复方法。
原因:配方行用空格缩进而不是 Tab。
cat -A Makefile | sed -n '14,18p' # 配方行应以 ^I 开头 sed -i 's/^ /\t/' Makefile # 把行首 4 个空格换成 Tab(先检查!)
原因:直接复制了 test/bats 目录而不是 git submodule add,或 .gitmodules 没有提交。
git rm --cached test/bats 2>/dev/null; rm -rf test/bats git submodule add https://github.com/bats-core/bats-core.git test/bats git add .gitmodules test/bats && git commit -m "test: add bats submodule"
actions/setup-python 某个标签对应的提交 SHA,用于固定。gh api repos/actions/setup-python/releases/latest --jq .tag_name
gh api repos/actions/setup-python/git/ref/tags/<标签> --jq '.object.sha + " " + .object.type'
# type 为 tag(附注标签)时,再查一次:gh api repos/actions/setup-python/git/tags/<sha> --jq .object.sha
# 或:git ls-remote https://github.com/actions/setup-python 'refs/tags/<标签>^{}'opsctl-1.0.0.tar.gz 与 .sha256,写出校验与安装命令。sha256sum -c opsctl-1.0.0.tar.gz.sha256 # macOS: shasum -a 256 -c tar -xzf opsctl-1.0.0.tar.gz && cd opsctl-1.0.0 && sh install.sh
① 增加一个矩阵作业:runs-on: [ubuntu-24.04, macos-15](macOS 上 brew install bash shellcheck shfmt,并确保 bash 指向 Homebrew 版本;runner 名称以 GitHub 文档为准);② 增加容器作业:container: bash:4.4 中运行 bash test/bats/bin/bats test/(Alpine 用户空间,需要 apk add make git 等),验证最低版本与 BusyBox 工具兼容性;③ 再加一步 sh bin/opsctl help 断言退出码 3(版本守卫);④ 矩阵作业失败不要阻塞发布作业之外的东西时,用 fail-fast: false 看到全部结果。
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
| 目的 | 命令 / 代码 |
|---|---|
| 整个脚本追踪 | bash -x script.sh;bash -xv 同时打印原始行 |
| 局部追踪(不打印 set +x) | set -x; …; { set +x; } 2>/dev/null |
| 实用 PS4 | PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '(必须单引号) |
| 带时间戳 | PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE[0]##*/}:${LINENO}: ' |
| 轨迹写文件 | exec {fd}>>trace.log; BASH_XTRACEFD=$fd; set -x |
| 语法检查 | bash -n f.sh;shfmt -d f.sh;dash -n f.sh |
| 调用栈 | caller 0;${FUNCNAME[i]} ${BASH_SOURCE[i]} ${BASH_LINENO[i-1]} |
| ERR trap | set -E; trap 'echo "ERR $? at ${BASH_SOURCE[0]}:$LINENO: $BASH_COMMAND" >&2' ERR |
| DEBUG trap | set -T; trap 'echo "> $BASH_COMMAND" >&2' DEBUG |
| 精确查看变量 | declare -p var arr |
| 代码 | 一句话 | 修复 |
|---|---|---|
| SC2086 (info) | 变量未加引号 | "$var";需要拆分时用数组 |
| SC2046 (warning) | 命令替换未加引号 | find -exec … {} +、mapfile |
| SC2155 (warning) | 声明与赋值合写,掩盖退出码 | local v; v=$(cmd) |
| SC2164 (warning) | cd 失败未处理 | cd -- "$d" || exit |
| SC2181 (style) | 用 $? 间接判断 | if ! cmd; then |
| SC2034 (warning) | 变量未使用 | 删除 / 修正拼写 / export |
| SC2045 (error) | 遍历 ls 输出 | for f in ./* |
| SC2115 (warning) | rm -rf $d/* | rm -rf -- "${d:?}"/* |
| SC2006 (style) | 反引号 | $(…) |
| SC1091 (info) | 未跟随 source | -x + # shellcheck source=… |
| SC3xxx | POSIX sh 中的不可移植写法 | 见 M6 |
shellcheck -x -S warning bin/opsctl lib/*.sh # 门禁 shellcheck -f gcc f.sh # 编辑器友好 shellcheck -f diff f.sh | git apply # 自动修复(部分规则) # shellcheck disable=SC2086 # 理由…… (单条命令) # shellcheck shell=bash (库文件第一行)
shfmt -d bin/opsctl lib test/*.bats # CI:有差异则失败(读取 .editorconfig) shfmt -l -w bin/opsctl lib # 改写 shfmt -i 2 -ci -bn f.sh # 命令行参数(会忽略 .editorconfig!) # .editorconfig:[*.sh] indent_style=space indent_size=2 shell_variant=bash switch_case_indent=true binary_next_line=true
Google 风格要点:只用 Bash;2 空格 / 80 列;main "$@";pkg::func;local 与命令替换赋值分开;[[ ]]、$( );错误写 stderr;库 .sh 不可执行;超过 100 行考虑换语言。
#!/usr/bin/env bats
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
STUB_BIN="$BATS_TEST_TMPDIR/bin"; mkdir -p "$STUB_BIN"; export PATH="$STUB_BIN:$PATH"
}
teardown() { :; } # 总会运行
@test "描述" {
run --separate-stderr ./bin/opsctl nope
assert_failure 2
refute_output
assert_stderr --partial '未知子命令'
}
| 断言 | 用途 |
|---|---|
assert_success / assert_failure [N] | 退出码 |
assert_output 'x' / --partial / --regexp / refute_output | 输出全等 / 包含 / 正则 / 为空 |
assert_line --index 0 'x' | 指定行 |
assert_equal "$actual" "$expected" | 两个值 |
assert_stderr(需 --separate-stderr) | stderr |
run -2 cmd / run ! cmd | run 时直接断言退出码 |
bats --tap / --report-formatter junit -o reports / -f 正则 / --jobs N | 运行选项 |
| 慢(外部命令) | 快(内建) |
|---|---|
$(basename "$f") / $(dirname "$f") | ${f##*/} / ${f%/*} |
$(echo "$s" | tr a-z A-Z) | ${s^^} |
$(date +%F) | printf -v d '%(%F)T' -1 |
$(cat f) | $(<f) |
echo "$s" | grep -q re | [[ $s =~ re ]] |
$(expr $n + 1) / ((n++)) | ((++n))(set -e 安全) |
| Bash 循环逐行处理大文件 | 一个 awk |
for f in …; do cmd "$f"; done | find … -exec cmd {} + / xargs -0 -P N |
TIMEFORMAT='%R s'; time func hyperfine -w 3 'bash a.sh' 'bash b.sh' strace -f -c -e trace=clone,clone3,execve bash a.sh
| Bash | POSIX sh |
|---|---|
[[ $a == b* ]] | case $a in b*) … ;; esac |
echo -e | printf |
source f | . ./f |
arr=(a b) | set -- a b |
cmd &> f | cmd >f 2>&1 |
function f { | f() { |
${x^^} / ${x:1:2} / ${x/a/b} | tr / cut / sed |
checkbashisms script.sh; shellcheck -s sh script.sh; dash -n script.sh
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash x.sh # macOS 自带 Bash 的版本
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh x.sh # BusyBox ash
# 版本守卫(opsctl 入口的写法:第一句是 POSIX,dash 执行到就退出):
if [ -z "${BASH_VERSION-}" ]; then echo "opsctl: please run with bash, not sh" >&2; exit 3; fi
if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 4) )); then
echo "opsctl: bash >= 4.4 required (found $BASH_VERSION)" >&2; exit 3
fi
> 100 行或控制流复杂 · 嵌套数据结构 · 大量 JSON/YAML · 浮点/日期/CSV · 细粒度错误处理 · 共享状态的并发 · 常驻服务 · Windows/大规模分发 · 不可信输入拼命令 · 优化到头仍不够快 · 多主机配置收敛(→ Ansible)· 云资源生命周期(→ Terraform)。
make check # lint + fmt-check + test echo 1.0.0 > VERSION && git commit -am "release: 1.0.0" && git tag -a v1.0.0 -m "opsctl 1.0.0" make release # git archive + sha256sum git push origin main v1.0.0 # CI 校验 VERSION==标签 并创建 Release # action 固定 SHA:uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
运维群里流传着一个 cleanup-logs.sh:删除 N 天前的 *.log,压缩 1 天以上的日志。它在 CentOS 上“一直好好的”,但在 Ubuntu 上报错,而且有人说它“删过家目录里的东西”。你的任务:在不改变预期行为的前提下,把它变成 opsctl 的 cleanup 子命令,有测试、零告警、可发布。
mkdir -p ~/bashlab/final && cd ~/bashlab/final
cat > cleanup-logs.sh <<'EOF'
#!/bin/sh
# cleanup-logs.sh —— 删除 N 天前的日志并压缩 1 天以上的日志(祖传版本:只用于分析,不要运行!)
LOG_DIR=$1
DAYS=${2:-7}
cd $LOG_DIR
for f in `ls *.log`; do
age=$(( ( $(date +%s) - $(stat -c %Y $f) ) / 86400 ))
if [ $age -gt $DAYS ]; then
rm $f
elif [[ $age -ge 1 ]]; then
gzip $f
fi
done
echo "done: $(ls | wc -l) files left"
EOF
dash -n cleanup-logs.sh; checkbashisms cleanup-logs.sh; shellcheck cleanup-logs.sh。写下至少 6 个问题,并标出哪一个能解释“删过家目录里的东西”(提示:LOG_DIR 为空时 cd 去了哪里?)。test/cleanup.bats 中用 $BATS_TEST_TMPDIR 构造目录:新文件、2 天前、10 天前的 .log,以及“怪名字”文件(含空格、以 - 开头,可从 ~/bashlab/data/files/ 复制)。修改时间用 touch -d '10 days ago' f(GNU;macOS 用 touch -t)。期望:10 天前的被删除、2 天前的变成 .gz、新的不动、怪名字文件被正确处理、目录参数为空或为 /、$HOME 时以退出码 2 拒绝执行。lib/cmd_cleanup.sh:cmd::cleanup <dir> [--days N] [--dry-run]。要求:参数校验(N 为正整数、目录存在);拒绝 / 与 $HOME;用 find "$dir" -maxdepth 1 -type f -name '*.log' -mtime +"$days" -delete 处理删除(-mtime +N 表示“整天数(舍去小数)大于 N”,与祖传脚本 age -gt DAYS 的整数除法语义一致;用测试确认边界)、用 -mtime +0 … -exec gzip -- {} + 批量压缩其余 1 天以上的日志;--dry-run 只打印;所有日志走 log::*,用法错误走 util::usage_error(2);同一目录的并发清理用第 4 课的 util::lock 防止。先故意不写第二行的 # opsctl-summary:,运行 test/bats/bin/bats -f summary test/opsctl.bats,确认 M4 的 summary 测试以 cmd_cleanup.sh 缺少 # opsctl-summary: 失败,再补上。make check 全绿(ShellCheck 零告警、shfmt 无差异、全部测试通过)。用 OPSCTL_TRACE=1 观察一次 --dry-run 的执行轨迹,确认 find 的参数都被正确引用。find 版本:hyperfine -w 1 --prepare '…重建测试目录…' 'bash old.sh d 7' 'bin/opsctl cleanup d --days 7',记录倍数。find -maxdepth、-delete、stat -c、touch -d 在 GNU / BSD / BusyBox 上是否可用?在 bash:4.4(BusyBox 工具)容器中运行 test/cleanup.bats,把发现写进 README 的“已知限制”。VERSION、usage、CHANGELOG,打标签 v1.1.0,推送,确认 CI 的 release 作业生成 opsctl-1.1.0.tar.gz 与校验和。PS4 在每次打印轨迹前展开;双引号会让 ${LINENO}、${FUNCNAME} 在赋值时就被展开成固定值。PS4 的第一个字符按间接层级重复:命令替换在子 Shell 中执行,层级加一,所以显示 ++。
local v=$(cmd) 的退出码是 local 的(成功),cmd 的失败被掩盖;在 set -e 下脚本不会退出,带着空值继续执行,可能导致误操作。分开写 local v; v=$(cmd) 后,赋值语句的退出码就是 cmd 的退出码。
run 在子 Shell 中执行、捕获 $status/$output/${lines[@]},命令失败不会让测试失败——用于需要断言退出码或输出的场景。直接调用时 set -e 生效,失败立即让测试失败,且函数对变量的修改保留在测试进程中——用于准备步骤、或需要检查副作用(变量)的场景。
前提:被测脚本通过命令名调用外部程序、不重设 PATH、不写死绝对路径;替身有可执行权限与 shebang。局限:无法替换内建命令与 Shell 函数(可以在测试中重新定义函数来替换);同一进程内命令哈希可能缓存旧路径(hash -r);替身只模拟了你想到的行为,真实工具的边界情况仍需要集成测试。
看运行环境是否受控:容器入口、curl | sh 安装器、嵌入式、Debian 维护脚本等不受控或极简环境 → POSIX sh,并用 shellcheck -s sh、checkbashisms、dash/busybox 容器验证。运维工具、CI 脚本、开发者工具等受控环境 → Bash,声明最低版本并加版本守卫,在最低版本的容器中跑测试。关键是二选一并验证,不要写“看起来像 sh 的 bash”。
git archive <tag> 只包含该提交中被跟踪的文件,不含未提交修改、构建产物或本地配置,配合 export-ignore 控制内容,结果可复现、可校验。action 的标签可以被维护者或攻击者移动(如 2025 年 tj-actions 事件),提交 SHA 不可变;固定 SHA + Dependabot 审阅升级,在可复现与安全更新之间取得平衡。
| 主题 | 核实结论 | 来源(访问日期 2026-11-17) |
|---|---|---|
| Bash 版本 | Ubuntu 26.04(resolute)bash 5.3-2ubuntu1;上游 5.3 补丁到 bash53-020(5.3.20);本机实测环境为 Git for Windows 的 Bash 5.2.37 | packages.ubuntu.com;GNU FTP bash-5.3-patches |
| xtrace、PS4、BASH_XTRACEFD、caller、trap、EPOCHREALTIME | 语义按 Bash 手册;PS4 首字符按间接层级重复、BASH_XTRACEFD 的关闭行为;本课的轨迹输出均在 Bash 5.2.37 实际运行 | GNU Bash Reference Manual |
| ShellCheck | 最新 v0.11.0(2025-08-03):新增 SC2327–SC2332、SC3062;SC2002 改为默认关闭;SC2335 可选;Ubuntu 26.04 apt 为 0.11.0-2 | ShellCheck releases;packages.ubuntu.com |
| shfmt | 最新 v3.14.1(2026-09-06);3.14.0 新增 --detect、zsh 方言;.sh 扩展名默认按 posix 解析;带格式参数时忽略 EditorConfig;旧键名 shell_variant/switch_case_indent 仍被接受;Ubuntu 26.04 apt 为 3.12.0 | mvdan/sh releases;shfmt.1.scd(v3.14.1) |
| bats-core 与辅助库 | bats-core v1.14.0(2026-07-21):run 遵守函数内的 set -e、找不到测试时报错、新增 --errexit;bats-assert v2.2.4(2.2.0 起有 assert_stderr);bats-support v0.3.0;bats-file v0.4.0;Ubuntu 26.04 apt:bats 1.13.0、bats-assert 2.2.4、bats-support 0.3.0,库路径 /usr/lib/bats/ | bats-core releases;Writing tests;bats-assert;packages.ubuntu.com 文件列表 |
| Google Shell Style Guide | 100 行规则、只用 Bash、2 空格/80 列、:: 包分隔符、main、local 与命令替换分开、[[ ]]、错误写 STDERR、扩展名规则;指南未提及 shfmt | shellguide.html |
| dash / POSIX | Ubuntu 26.04 与 Debian 13 的 dash 为 0.5.12;pipefail 于 2024-04 合入 dash 主线(0.5.13);POSIX.1-2024 纳入 pipefail 与 $'…';本课 dash 行为在 Git for Windows 自带 dash 上实测 | packages.ubuntu.com;packages.debian.org;dash.git |
| 其他工具版本 | devscripts 2.26.7(checkbashisms)、hyperfine 1.19.0(apt)/ 2.0.0(上游 2026-10-07)、busybox 1.37.0、just 1.59.0 | packages.ubuntu.com;GitHub releases |
| 容器镜像标签 | bash:3.2(3.2.57)、bash:4.4(4.4.23)、bash:5.2、bash:5.3(5.3.20)、koalaman/shellcheck:v0.11.0、mvdan/shfmt:v3.14.1、bats/bats:1.14.0、busybox:1.37 均存在 | Docker Hub API |
| GitHub Actions | actions/checkout 最新 v7.0.1,标签指向提交 3d3c42e5aac5ba805825da76410c181273ba90b1;ShellCheck/shfmt 发布资产文件名按发布页核实 | GitHub API(gh api repos/actions/checkout/git/ref/tags/v7.0.1) |
所有视频均通过 YouTube oEmbed(https://www.youtube.com/oembed?url=…&format=json)于 2026-11-17 核实标题与频道:
| 视频 ID | 标题 | 频道 | 用于 |
|---|---|---|---|
| nvAMWPeKBrc | 10 Tips for debugging Bash Scripts (actually useful and real-world applicable) | You Suck at Programming | M1 |
| LX-APA9ugMc | Bash Debug Mode Explained | You Suck at Programming | M1 |
| Yw5qLN5bKPg | Debugging Bash Scripts: The Power of set -e, set -x, set -o, and set -u | Daily Dose of Dev | M1 |
| 28Ygo05cLmo | Linting and Improving Your Bash Scripts with ShellCheck | Nick Janetakis | M2 |
| zFDYVzU6JxA | I Learned Something New about Bash from `shellcheck` | You Suck at Programming | M2 |
| GToQwmDXUx8 | SC2086: The Bash Quoting Bug to Fix Before You Schedule a Script | FutureOps | M2 |
| lmt7rrMW_pU | Write Better Bash Scripts! Use ShellCheck and shfmt | Tom on the Internet | M3 |
| OqWacbx5rLo | Create BULLET PROOF Shell Scripts with ShellCheck and Neovim! | DevOps Toolbox | M3 |
| SB7e5qdGh9E | How to Test Docker Images and Shell Scripts (with bats-core) | Redhwan Nacef | M4、M8 |
| EHUE3i8izew | Test-Driven Development (TDD) Tutorial: Unit Testing Bash Scripts with Bats on Rocky Linux 10 | theurbanpenguin | M4 |
| sJ5LHe22IU0 | fork and exec Explained #bash | Truly Coding | M5 |
| hl3siAyoQ-w | Bash Scripting : Source and Fork your Scripts | theurbanpenguin | M5 |
| oKA2aK0-tb4 | "Overcoming the limitations of the POSIX shell command language" - Curtis Millar (LCA 2021 Online) | linux.conf.au | M6 |
| PPiPbMFKDHY | My thoughts on bash vs. Posix Compliant Shell Scripts. I am Mr. You Suck at Programming. | You Suck at Programming | M6 |
| LjGwm0Z6D24 | Shell Script Tutorial: A Look At Posix Compliant Shell Operators | Brodie Robertson | M6 |
| RQEh8XW0wLk | Python or Bash for scripting? Which is best? | Mashed | M7 |
| ASTpo4e7q9c | Python vs. Bash: Why Python CRUSHED Bash for DevOps Automation | TechTalks with Gil - SRE | M7 |
| BQrohJ3PT7I | How to use GitHub Actions | GitHub for Beginners | GitHub | M8 |
| UrODXOiqH0k | GitHub Actions: Protecting Your CI from Attackers | SANS Cloud Security | M8 |
M5 未找到经核实、专门讲 Bash 性能优化的视频,已提供分镜脚本。小频道视频仅作补充,内容以本课与官方文档为准。
“语音”分页使用浏览器内置的 Web Speech API(speechSynthesis,zh-CN 语音)实时朗读讲解稿,英文术语用 en-US 语音朗读。本课件无法内嵌或生成 MP3 文件;需要音频时,可把讲解稿交给任意 TTS 工具。
bash -n 的 “unexpected end of file” 会补充未闭合的复合命令信息)未在 5.3 上实测。log.sh、util.sh 追加部分、cmd_export.sh、cmd_doctor.sh、bin/opsctl、test/flaky.sh)、第 5 课模块 8(cmd_logs.sh、logs_report.awk、配置键)与第 6 课模块 8(版本号 sed、8 个配置键、cmd_health.sh、cmd_backup.sh、cmd_deploy.sh、config show 键列表)重建了 v0.3.0,再套用本课的 VERSION 修改,在本机 Bash 5.2 与 dash 上直接运行,核对了每个测试依赖的行为:-V、8 个子命令的 summary 与 help <name>、未知子命令/无参数的退出码 2、servers list 的表格与 tsv、非法 env 2、缺参数 2、数据目录不可读 1、优先级(--env 压过 OPSCTL_ENV 且默认无 stderr,-v 时一行 DEBUG)、health 的退出码 0/1/2、日志文字、curl 参数、OPSCTL_HEALTH_RETRIES 与 -r 的优先级、全抖动等待的上界、util::retry 差一 bug 导致 5 次调用、logs report 的金标准与错误路径、util::csv_split、log::info 的 [PID] 格式、dash 下守卫返回 3。*.bats 文件本身未在本机用 bats 执行。logs report 未被修改,M7 另建 codes 子命令演示迁移。shfmt -d 很可能有 diff);运行 make fmt 审阅后单独提交。ubuntu-24.04 runner 的可用性与预装软件以 GitHub 文档为准。/bin/sh 的实现细节(Bash 3.2 POSIX 模式,可切换 dash)来自 Apple 平台的公开资料与社区文档。strace 实测值可能略少。