bash-style-guide
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBash Style Guide
Bash 脚本风格指南
Scope Boundaries
适用范围界定
- Use this skill when the task matches the trigger condition described in .
description - Do not use this skill when the primary task falls outside this skill's domain.
Use this skill to write and review Bash scripts that are safe, debuggable, and operable in CI and production automation.
- 当任务符合中描述的触发条件时,使用本技能。
description - 当主要任务超出本技能的适用领域时,请勿使用。
使用本技能编写和审查可在CI与生产自动化环境中安全运行、便于调试的Bash脚本。
Trigger And Co-activation Reference
触发与协同激活参考
- If available, use for canonical co-activation rules.
references/trigger-matrix.md - If available, resolve style-guide activation from changed files with .
python3 scripts/resolve_style_guides.py <changed-path>... - If available, validate trigger matrix consistency with .
python3 scripts/validate_trigger_matrix_sync.py
- 若有可用的,请以此作为标准的协同激活规则。
references/trigger-matrix.md - 若有可用工具,可通过根据变更文件确定应激活的风格指南。
python3 scripts/resolve_style_guides.py <changed-path>... - 若有可用工具,可通过验证触发矩阵的一致性。
python3 scripts/validate_trigger_matrix_sync.py
Quality Gate Command Reference
质量门命令参考
- If available, use for CI check-only and local autofix mapping.
references/quality-gate-command-matrix.md
- 若有可用的,请以此作为CI仅检查模式与本地自动修复的映射参考。
references/quality-gate-command-matrix.md
Quick Start Snippets
快速入门代码片段
Script skeleton with strict mode and cleanup trap
包含严格模式与清理陷阱的脚本骨架
bash
#!/usr/bin/env bash
set -euo pipefail
readonly SCRIPT_NAME="$(basename "$0")"
readonly TEMP_DIR="$(mktemp -d)"
cleanup() {
rm -rf -- "${TEMP_DIR}"
}
on_error() {
local line="$1"
local exit_code="$2"
echo "${SCRIPT_NAME}: failed at line ${line} (exit=${exit_code})" >&2
}
trap cleanup EXIT
trap 'on_error "$LINENO" "$?"' ERR
main() {
echo "working dir: ${TEMP_DIR}"
}
main "$@"bash
#!/usr/bin/env bash
set -euo pipefail
readonly SCRIPT_NAME="$(basename "$0")"
readonly TEMP_DIR="$(mktemp -d)"
cleanup() {
rm -rf -- "${TEMP_DIR}"
}
on_error() {
local line="$1"
local exit_code="$2"
echo "${SCRIPT_NAME}: failed at line ${line} (exit=${exit_code})" >&2
}
trap cleanup EXIT
trap 'on_error "$LINENO" "$?"' ERR
main() {
echo "working dir: ${TEMP_DIR}"
}
main "$@"Required environment variable check (fail fast)
必要环境变量检查(快速失败)
bash
: "${API_TOKEN:?API_TOKEN is required}"
: "${API_BASE_URL:?API_BASE_URL is required}"bash
: "${API_TOKEN:?API_TOKEN is required}"
: "${API_BASE_URL:?API_BASE_URL is required}"Safe command assembly with arrays
使用数组安全组装命令
bash
run_curl() {
local url="$1"
local -a args=(
--fail
--silent
--show-error
--header "Authorization: Bearer ${API_TOKEN}"
"${url}"
)
curl "${args[@]}"
}bash
run_curl() {
local url="$1"
local -a args=(
--fail
--silent
--show-error
--header "Authorization: Bearer ${API_TOKEN}"
"${url}"
)
curl "${args[@]}"
}Bounded retry with explicit backoff constants
带显式退避常量的有限重试
bash
readonly MAX_ATTEMPTS=5
readonly RETRY_DELAY_SECONDS=2
retry_command() {
local attempt=1
while (( attempt <= MAX_ATTEMPTS )); do
if "$@"; then
return 0
fi
if (( attempt == MAX_ATTEMPTS )); then
echo "command failed after ${MAX_ATTEMPTS} attempts" >&2
return 1
fi
sleep "${RETRY_DELAY_SECONDS}"
((attempt++))
done
}bash
readonly MAX_ATTEMPTS=5
readonly RETRY_DELAY_SECONDS=2
retry_command() {
local attempt=1
while (( attempt <= MAX_ATTEMPTS )); do
if "$@"; then
return 0
fi
if (( attempt == MAX_ATTEMPTS )); then
echo "command failed after ${MAX_ATTEMPTS} attempts" >&2
return 1
fi
sleep "${RETRY_DELAY_SECONDS}"
((attempt++))
done
}Safe line reading preserving whitespace
保留空白符的安全行读取
bash
while IFS= read -r line; do
printf 'line=%s\n' "${line}"
done < "${input_file}"bash
while IFS= read -r line; do
printf 'line=%s\n' "${line}"
done < "${input_file}"Structure And Readability
结构与可读性
- Use for executable scripts.
#!/usr/bin/env bash - For executable entrypoints, use strict mode: .
set -euo pipefail - Keep functions focused on one responsibility and use for orchestration.
main - Use uppercase constants () and lowercase locals (
MAX_RETRIES).retry_count - Use inside functions to avoid state leakage.
local - Add short intent comments only for non-obvious logic.
- 可执行脚本请使用。
#!/usr/bin/env bash - 可执行入口点请启用严格模式:。
set -euo pipefail - 函数应聚焦单一职责,使用函数进行编排。
main - 常量使用大写(如),局部变量使用小写(如
MAX_RETRIES)。retry_count - 函数内部使用声明变量,避免状态泄漏。
local - 仅为非显而易见的逻辑添加简短的意图注释。
Data Handling And Quoting
数据处理与引号使用
- Quote expansions by default: ,
"${var}"."${array[@]}" - Use arrays for argument lists; avoid string-concatenated command assembly.
- Replace magic numbers with named constants including units ().
TIMEOUT_SECONDS - Avoid ; treat it as a security-sensitive last resort.
eval - Fail fast for required environment variables; do not add silent defaults for required config.
- 默认对扩展内容加引号:、
"${var}"。"${array[@]}" - 使用数组存储参数列表;避免通过字符串拼接组装命令。
- 用带单位的命名常量替代魔法数字(如)。
TIMEOUT_SECONDS - 避免使用;将其视为敏感安全场景下的最后手段。
eval - 必要环境变量缺失时快速失败;请勿为必要配置添加静默默认值。
Error Handling And Control Flow
错误处理与控制流
- Return explicit non-zero codes for expected failure modes.
- Use for cleanup and actionable error reporting.
trap - Handle failure paths intentionally () instead of masking.
if ! cmd; then ... fi - Avoid broad ; suppress only with explicit rationale.
|| true - Let failures surface when root cause should be fixed.
- 针对预期的失败场景返回明确的非零状态码。
- 使用进行清理操作并生成可操作的错误报告。
trap - 主动处理失败路径(如),而非掩盖错误。
if ! cmd; then ... fi - 避免宽泛的;仅在有明确理由时才抑制错误。
|| true - 当根本原因需要修复时,让失败直接暴露。
Security And Operational Safety
安全与运维安全性
- Validate all external input before use.
- Use before positional paths in destructive commands (
--).rm -- "$target" - Prefer for temporary files/directories.
mktemp - Never print secrets or tokens in logs.
- Use least privilege and avoid unnecessary .
sudo
- 使用前验证所有外部输入。
- 破坏性命令中,在路径参数前使用(如
--)。rm -- "$target" - 优先使用创建临时文件/目录。
mktemp - 切勿在日志中打印密钥或令牌等敏感信息。
- 遵循最小权限原则,避免不必要的。
sudo
Performance And Scalability
性能与可扩展性
- Avoid subshell spawning in tight loops when builtins suffice.
- Prefer single-pass text processing over repeated pipelines.
- Batch filesystem operations where practical.
- Use bounded retry loops with named backoff constants.
- 当内置命令可满足需求时,避免在密集循环中生成子shell。
- 优先使用单次遍历的文本处理,而非重复的管道操作。
- 尽可能批量执行文件系统操作。
- 使用带命名退避常量的有限重试循环。
Testing And Verification
测试与验证
- Add tests for critical behavior and failure paths.
bats - Cover edge cases: empty input, whitespace paths, missing env vars, timeout, retry exhaustion.
- Document manual verification where automation is not feasible.
- Check idempotency for scripts that may run repeatedly.
- 为关键行为与失败路径添加测试。
bats - 覆盖边缘场景:空输入、含空白符的路径、缺失的环境变量、超时、重试耗尽。
- 在无法自动化的场景下,记录手动验证步骤。
- 检查可能重复运行的脚本的幂等性。
Minimal bats
example
bats最简bats
示例
batsbash
#!/usr/bin/env bats
@test "fails when required env var is missing" {
run ./script.sh
[ "$status" -ne 0 ]
[[ "$output" == *"API_TOKEN is required"* ]]
}bash
#!/usr/bin/env bats
@test "fails when required env var is missing" {
run ./script.sh
[ "$status" -ne 0 ]
[[ "$output" == *"API_TOKEN is required"* ]]
}CI Required Quality Gates (check-only)
CI 必填质量门(仅检查模式)
- Run with warnings treated as actionable.
shellcheck - Run (or equivalent check mode) and require zero diff.
shfmt -d - Run test suite (or repository-specific path).
bats test/ - Reject changes that hide failures or rely on implicit behavior.
- 运行,将警告视为需处理的问题。
shellcheck - 运行(或等效的检查模式),要求无差异。
shfmt -d - 运行测试套件(如或仓库指定路径)。
bats test/ - 拒绝隐藏失败或依赖隐式行为的变更。
Optional Autofix Commands (local)
可选本地自动修复命令
- Run .
shfmt -w - Apply safe mechanical fixes suggested by , then rerun checks.
shellcheck
- 运行。
shfmt -w - 应用建议的安全自动修复,然后重新运行检查。
shellcheck