bash-style-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bash 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
    references/trigger-matrix.md
    for canonical co-activation rules.
  • 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
    references/quality-gate-command-matrix.md
    for CI check-only and local autofix mapping.
  • 若有可用的
    references/quality-gate-command-matrix.md
    ,请以此作为CI仅检查模式与本地自动修复的映射参考。

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

结构与可读性

  1. Use
    #!/usr/bin/env bash
    for executable scripts.
  2. For executable entrypoints, use strict mode:
    set -euo pipefail
    .
  3. Keep functions focused on one responsibility and use
    main
    for orchestration.
  4. Use uppercase constants (
    MAX_RETRIES
    ) and lowercase locals (
    retry_count
    ).
  5. Use
    local
    inside functions to avoid state leakage.
  6. Add short intent comments only for non-obvious logic.
  1. 可执行脚本请使用
    #!/usr/bin/env bash
  2. 可执行入口点请启用严格模式:
    set -euo pipefail
  3. 函数应聚焦单一职责,使用
    main
    函数进行编排。
  4. 常量使用大写(如
    MAX_RETRIES
    ),局部变量使用小写(如
    retry_count
    )。
  5. 函数内部使用
    local
    声明变量,避免状态泄漏。
  6. 仅为非显而易见的逻辑添加简短的意图注释。

Data Handling And Quoting

数据处理与引号使用

  1. Quote expansions by default:
    "${var}"
    ,
    "${array[@]}"
    .
  2. Use arrays for argument lists; avoid string-concatenated command assembly.
  3. Replace magic numbers with named constants including units (
    TIMEOUT_SECONDS
    ).
  4. Avoid
    eval
    ; treat it as a security-sensitive last resort.
  5. Fail fast for required environment variables; do not add silent defaults for required config.
  1. 默认对扩展内容加引号:
    "${var}"
    "${array[@]}"
  2. 使用数组存储参数列表;避免通过字符串拼接组装命令。
  3. 用带单位的命名常量替代魔法数字(如
    TIMEOUT_SECONDS
    )。
  4. 避免使用
    eval
    ;将其视为敏感安全场景下的最后手段。
  5. 必要环境变量缺失时快速失败;请勿为必要配置添加静默默认值。

Error Handling And Control Flow

错误处理与控制流

  1. Return explicit non-zero codes for expected failure modes.
  2. Use
    trap
    for cleanup and actionable error reporting.
  3. Handle failure paths intentionally (
    if ! cmd; then ... fi
    ) instead of masking.
  4. Avoid broad
    || true
    ; suppress only with explicit rationale.
  5. Let failures surface when root cause should be fixed.
  1. 针对预期的失败场景返回明确的非零状态码。
  2. 使用
    trap
    进行清理操作并生成可操作的错误报告。
  3. 主动处理失败路径(如
    if ! cmd; then ... fi
    ),而非掩盖错误。
  4. 避免宽泛的
    || true
    ;仅在有明确理由时才抑制错误。
  5. 当根本原因需要修复时,让失败直接暴露。

Security And Operational Safety

安全与运维安全性

  1. Validate all external input before use.
  2. Use
    --
    before positional paths in destructive commands (
    rm -- "$target"
    ).
  3. Prefer
    mktemp
    for temporary files/directories.
  4. Never print secrets or tokens in logs.
  5. Use least privilege and avoid unnecessary
    sudo
    .
  1. 使用前验证所有外部输入。
  2. 破坏性命令中,在路径参数前使用
    --
    (如
    rm -- "$target"
    )。
  3. 优先使用
    mktemp
    创建临时文件/目录。
  4. 切勿在日志中打印密钥或令牌等敏感信息。
  5. 遵循最小权限原则,避免不必要的
    sudo

Performance And Scalability

性能与可扩展性

  1. Avoid subshell spawning in tight loops when builtins suffice.
  2. Prefer single-pass text processing over repeated pipelines.
  3. Batch filesystem operations where practical.
  4. Use bounded retry loops with named backoff constants.
  1. 当内置命令可满足需求时,避免在密集循环中生成子shell。
  2. 优先使用单次遍历的文本处理,而非重复的管道操作。
  3. 尽可能批量执行文件系统操作。
  4. 使用带命名退避常量的有限重试循环。

Testing And Verification

测试与验证

  1. Add
    bats
    tests for critical behavior and failure paths.
  2. Cover edge cases: empty input, whitespace paths, missing env vars, timeout, retry exhaustion.
  3. Document manual verification where automation is not feasible.
  4. Check idempotency for scripts that may run repeatedly.
  1. 为关键行为与失败路径添加
    bats
    测试。
  2. 覆盖边缘场景:空输入、含空白符的路径、缺失的环境变量、超时、重试耗尽。
  3. 在无法自动化的场景下,记录手动验证步骤。
  4. 检查可能重复运行的脚本的幂等性。

Minimal
bats
example

最简
bats
示例

bash
#!/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 必填质量门(仅检查模式)

  1. Run
    shellcheck
    with warnings treated as actionable.
  2. Run
    shfmt -d
    (or equivalent check mode) and require zero diff.
  3. Run test suite (
    bats test/
    or repository-specific path).
  4. Reject changes that hide failures or rely on implicit behavior.
  1. 运行
    shellcheck
    ,将警告视为需处理的问题。
  2. 运行
    shfmt -d
    (或等效的检查模式),要求无差异。
  3. 运行测试套件(如
    bats test/
    或仓库指定路径)。
  4. 拒绝隐藏失败或依赖隐式行为的变更。

Optional Autofix Commands (local)

可选本地自动修复命令

  1. Run
    shfmt -w
    .
  2. Apply safe mechanical fixes suggested by
    shellcheck
    , then rerun checks.
  1. 运行
    shfmt -w
  2. 应用
    shellcheck
    建议的安全自动修复,然后重新运行检查。