bash-pro

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Use this skill when

适用场景

  • Writing or reviewing Bash scripts for automation, CI/CD, or ops
  • Hardening shell scripts for safety and portability
  • 编写或审查用于自动化、CI/CD或运维的Bash脚本
  • 强化Shell脚本以提升安全性和可移植性

Do not use this skill when

不适用场景

  • You need POSIX-only shell without Bash features
  • The task requires a higher-level language for complex logic
  • You need Windows-native scripting (PowerShell)
  • 你需要仅支持POSIX标准的Shell,无需Bash特性
  • 任务需要使用更高级的语言处理复杂逻辑
  • 你需要Windows原生脚本(PowerShell)

Instructions

操作指南

  1. Define script inputs, outputs, and failure modes.
  2. Apply strict mode and safe argument parsing.
  3. Implement core logic with defensive patterns.
  4. Add tests and linting with Bats and ShellCheck.
  1. 定义脚本的输入、输出和失败模式。
  2. 应用严格模式和安全的参数解析。
  3. 使用防御性模式实现核心逻辑。
  4. 通过Bats和ShellCheck添加测试与代码检查。

Safety

安全规范

  • Treat input as untrusted; avoid eval and unsafe globbing.
  • Prefer dry-run modes before destructive actions.
  • 将所有输入视为不可信内容;避免使用eval和不安全的通配符匹配。
  • 在执行破坏性操作前,优先使用试运行模式。

Focus Areas

核心关注领域

  • Defensive programming with strict error handling
  • POSIX compliance and cross-platform portability
  • Safe argument parsing and input validation
  • Robust file operations and temporary resource management
  • Process orchestration and pipeline safety
  • Production-grade logging and error reporting
  • Comprehensive testing with Bats framework
  • Static analysis with ShellCheck and formatting with shfmt
  • Modern Bash 5.x features and best practices
  • CI/CD integration and automation workflows
  • 带有严格错误处理的防御性编程
  • POSIX合规性与跨平台可移植性
  • 安全的参数解析与输入验证
  • 可靠的文件操作与临时资源管理
  • 流程编排与流水线安全
  • 生产级日志与错误报告
  • 基于Bats框架的全面测试
  • 借助ShellCheck的静态分析与shfmt的代码格式化
  • 现代Bash 5.x特性与最佳实践
  • CI/CD集成与自动化工作流

Approach

实施方法

  • Always use strict mode with
    set -Eeuo pipefail
    and proper error trapping
  • Quote all variable expansions to prevent word splitting and globbing issues
  • Prefer arrays and proper iteration over unsafe patterns like
    for f in $(ls)
  • Use
    [[ ]]
    for Bash conditionals, fall back to
    [ ]
    for POSIX compliance
  • Implement comprehensive argument parsing with
    getopts
    and usage functions
  • Create temporary files and directories safely with
    mktemp
    and cleanup traps
  • Prefer
    printf
    over
    echo
    for predictable output formatting
  • Use command substitution
    $()
    instead of backticks for readability
  • Implement structured logging with timestamps and configurable verbosity
  • Design scripts to be idempotent and support dry-run modes
  • Use
    shopt -s inherit_errexit
    for better error propagation in Bash 4.4+
  • Employ
    IFS=$'\n\t'
    to prevent unwanted word splitting on spaces
  • Validate inputs with
    : "${VAR:?message}"
    for required environment variables
  • End option parsing with
    --
    and use
    rm -rf -- "$dir"
    for safe operations
  • Support
    --trace
    mode with
    set -x
    opt-in for detailed debugging
  • Use
    xargs -0
    with NUL boundaries for safe subprocess orchestration
  • Employ
    readarray
    /
    mapfile
    for safe array population from command output
  • Implement robust script directory detection:
    SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
  • Use NUL-safe patterns:
    find -print0 | while IFS= read -r -d '' file; do ...; done
  • 始终使用
    set -Eeuo pipefail
    严格模式,并配置适当的错误捕获
  • 对所有变量扩展添加引号,以防止分词和通配符匹配问题
  • 优先使用数组和正确的迭代方式,避免
    for f in $(ls)
    这类不安全模式
  • Bash条件判断使用
    [[ ]]
    ,若需POSIX合规则回退到
    [ ]
  • 借助
    getopts
    和使用函数实现全面的参数解析
  • 通过
    mktemp
    和清理陷阱安全创建临时文件与目录
  • 优先使用
    printf
    而非
    echo
    以实现可预测的输出格式化
  • 使用命令替换
    $()
    而非反引号,提升可读性
  • 实现带时间戳和可配置日志级别的结构化日志
  • 设计脚本为幂等性,并支持试运行模式
  • Bash 4.4+版本中使用
    shopt -s inherit_errexit
    优化错误传播
  • 设置
    IFS=$'\n\t'
    以避免空格导致的意外分词
  • 使用
    : "${VAR:?message}"
    验证必填环境变量
  • 使用
    --
    结束选项解析,通过
    rm -rf -- "$dir"
    执行安全操作
  • 支持通过
    set -x
    启用
    --trace
    模式以进行详细调试
  • 使用
    xargs -0
    结合NUL分隔符实现安全的子流程编排
  • 借助
    readarray
    /
    mapfile
    从命令输出安全填充数组
  • 实现可靠的脚本目录检测:
    SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
  • 使用NUL安全模式:
    find -print0 | while IFS= read -r -d '' file; do ...; done

Compatibility & Portability

兼容性与可移植性

  • Use
    #!/usr/bin/env bash
    shebang for portability across systems
  • Check Bash version at script start:
    (( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))
    for Bash 4.4+ features
  • Validate required external commands exist:
    command -v jq &>/dev/null || exit 1
  • Detect platform differences:
    case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac
  • Handle GNU vs BSD tool differences (e.g.,
    sed -i
    vs
    sed -i ''
    )
  • Test scripts on all target platforms (Linux, macOS, BSD variants)
  • Document minimum version requirements in script header comments
  • Provide fallback implementations for platform-specific features
  • Use built-in Bash features over external commands when possible for portability
  • Avoid bashisms when POSIX compliance is required, document when using Bash-specific features
  • 使用
    #!/usr/bin/env bash
    shebang以实现跨系统可移植性
  • 脚本启动时检查Bash版本:若需Bash 4.4+特性,使用
    (( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))
  • 验证所需外部命令是否存在:
    command -v jq &>/dev/null || exit 1
  • 检测平台差异:
    case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac
  • 处理GNU与BSD工具差异(如
    sed -i
    vs
    sed -i ''
  • 在所有目标平台(Linux、macOS、BSD变体)上测试脚本
  • 在脚本头部注释中记录最低版本要求
  • 为平台特定特性提供回退实现
  • 为提升可移植性,优先使用Bash内置功能而非外部命令
  • 若需POSIX合规则避免Bash特有语法,使用Bash专属特性时需注明

Readability & Maintainability

可读性与可维护性

  • Use long-form options in scripts for clarity:
    --verbose
    instead of
    -v
  • Employ consistent naming: snake_case for functions/variables, UPPER_CASE for constants
  • Add section headers with comment blocks to organize related functions
  • Keep functions under 50 lines; refactor larger functions into smaller components
  • Group related functions together with descriptive section headers
  • Use descriptive function names that explain purpose:
    validate_input_file
    not
    check_file
  • Add inline comments for non-obvious logic, avoid stating the obvious
  • Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)
  • Place opening braces on same line for consistency:
    function_name() {
  • Use blank lines to separate logical blocks within functions
  • Document function parameters and return values in header comments
  • Extract magic numbers and strings to named constants at top of script
  • 脚本中使用长选项以提升清晰度:如
    --verbose
    而非
    -v
  • 采用一致的命名规范:函数/变量使用蛇形命名法(snake_case),常量使用大写(UPPER_CASE)
  • 使用注释块添加章节标题,组织相关函数
  • 函数代码控制在50行以内;将较大的函数重构为更小的组件
  • 将相关函数分组,并添加描述性章节标题
  • 使用能说明功能的函数名称:如
    validate_input_file
    而非
    check_file
  • 为非显而易见的逻辑添加行内注释,避免陈述显而易见的内容
  • 保持一致的缩进(2或4个空格,禁止混合使用制表符和空格)
  • 保持大括号与函数名同行:
    function_name() {
  • 使用空行分隔函数内的逻辑块
  • 在函数头部注释中记录参数与返回值
  • 将魔法数字和字符串提取为脚本顶部的命名常量

Safety & Security Patterns

安全与安全模式

  • Declare constants with
    readonly
    to prevent accidental modification
  • Use
    local
    keyword for all function variables to avoid polluting global scope
  • Implement
    timeout
    for external commands:
    timeout 30s curl ...
    prevents hangs
  • Validate file permissions before operations:
    [[ -r "$file" ]] || exit 1
  • Use process substitution
    <(command)
    instead of temporary files when possible
  • Sanitize user input before using in commands or file operations
  • Validate numeric input with pattern matching:
    [[ $num =~ ^[0-9]+$ ]]
  • Never use
    eval
    on user input; use arrays for dynamic command construction
  • Set restrictive umask for sensitive operations:
    (umask 077; touch "$secure_file")
  • Log security-relevant operations (authentication, privilege changes, file access)
  • Use
    --
    to separate options from arguments:
    rm -rf -- "$user_input"
  • Validate environment variables before using:
    : "${REQUIRED_VAR:?not set}"
  • Check exit codes of all security-critical operations explicitly
  • Use
    trap
    to ensure cleanup happens even on abnormal exit
  • 使用
    readonly
    声明常量,防止意外修改
  • 所有函数变量使用
    local
    关键字,避免污染全局作用域
  • 为外部命令设置超时:
    timeout 30s curl ...
    防止进程挂起
  • 操作前验证文件权限:
    [[ -r "$file" ]] || exit 1
  • 尽可能使用进程替换
    <(command)
    而非临时文件
  • 在命令或文件操作前清理用户输入
  • 使用模式匹配验证数值输入:
    [[ $num =~ ^[0-9]+$ ]]
  • 绝不对用户输入使用
    eval
    ;使用数组构建动态命令
  • 敏感操作设置严格的umask:
    (umask 077; touch "$secure_file")
  • 记录安全相关操作(认证、权限变更、文件访问)
  • 使用
    --
    分隔选项与参数:
    rm -rf -- "$user_input"
  • 使用前验证环境变量:
    : "${REQUIRED_VAR:?not set}"
  • 显式检查所有安全关键操作的退出码
  • 使用
    trap
    确保异常退出时仍能执行清理操作

Performance Optimization

性能优化

  • Avoid subshells in loops; use
    while read
    instead of
    for i in $(cat file)
  • Use Bash built-ins over external commands:
    [[ ]]
    instead of
    test
    ,
    ${var//pattern/replacement}
    instead of
    sed
  • Batch operations instead of repeated single operations (e.g., one
    sed
    with multiple expressions)
  • Use
    mapfile
    /
    readarray
    for efficient array population from command output
  • Avoid repeated command substitutions; store result in variable once
  • Use arithmetic expansion
    $(( ))
    instead of
    expr
    for calculations
  • Prefer
    printf
    over
    echo
    for formatted output (faster and more reliable)
  • Use associative arrays for lookups instead of repeated grepping
  • Process files line-by-line for large files instead of loading entire file into memory
  • Use
    xargs -P
    for parallel processing when operations are independent
  • 避免在循环中使用子shell;使用
    while read
    而非
    for i in $(cat file)
  • 优先使用Bash内置功能而非外部命令:如
    [[ ]]
    而非
    test
    ${var//pattern/replacement}
    而非
    sed
  • 批量操作替代重复的单次操作(如一个
    sed
    命令包含多个表达式)
  • 使用
    mapfile
    /
    readarray
    高效从命令输出填充数组
  • 避免重复的命令替换;将结果存储到变量中复用
  • 使用算术扩展
    $(( ))
    而非
    expr
    进行计算
  • 优先使用
    printf
    而非
    echo
    生成格式化输出(更快更可靠)
  • 使用关联数组实现查找,替代重复的grep操作
  • 处理大文件时逐行读取,而非将整个文件加载到内存
  • 操作相互独立时,使用
    xargs -P
    实现并行处理

Documentation Standards

文档规范

  • Implement
    --help
    and
    -h
    flags showing usage, options, and examples
  • Provide
    --version
    flag displaying script version and copyright information
  • Include usage examples in help output for common use cases
  • Document all command-line options with descriptions of their purpose
  • List required vs optional arguments clearly in usage message
  • Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures
  • Include prerequisites section listing required commands and versions
  • Add header comment block with script purpose, author, and modification date
  • Document environment variables the script uses or requires
  • Provide troubleshooting section in help for common issues
  • Generate documentation with
    shdoc
    from special comment formats
  • Create man pages using
    shellman
    for system integration
  • Include architecture diagrams using Mermaid or GraphViz for complex scripts
  • 实现
    --help
    -h
    标志,展示使用方法、选项和示例
  • 提供
    --version
    标志,显示脚本版本和版权信息
  • 在帮助输出中添加常见用例的使用示例
  • 记录所有命令行选项及其用途
  • 在使用说明中明确区分必填与可选参数
  • 记录退出码:0表示成功,1表示通用错误,特定错误使用特定代码
  • 添加先决条件章节,列出所需命令及版本
  • 添加包含脚本用途、作者和修改日期的头部注释块
  • 记录脚本使用或需要的环境变量
  • 在帮助中添加常见问题的故障排除章节
  • 通过特殊注释格式,使用
    shdoc
    生成文档
  • 使用
    shellman
    创建手册页以实现系统集成
  • 为复杂脚本添加基于Mermaid或GraphViz的架构图

Modern Bash Features (5.x)

现代Bash特性(5.x版本)

  • Bash 5.0: Associative array improvements,
    ${var@U}
    uppercase conversion,
    ${var@L}
    lowercase
  • Bash 5.1: Enhanced
    ${parameter@operator}
    transformations,
    compat
    shopt options for compatibility
  • Bash 5.2:
    varredir_close
    option, improved
    exec
    error handling,
    EPOCHREALTIME
    microsecond precision
  • Check version before using modern features:
    [[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]
  • Use
    ${parameter@Q}
    for shell-quoted output (Bash 4.4+)
  • Use
    ${parameter@E}
    for escape sequence expansion (Bash 4.4+)
  • Use
    ${parameter@P}
    for prompt expansion (Bash 4.4+)
  • Use
    ${parameter@A}
    for assignment format (Bash 4.4+)
  • Employ
    wait -n
    to wait for any background job (Bash 4.3+)
  • Use
    mapfile -d delim
    for custom delimiters (Bash 4.4+)
  • Bash 5.0:关联数组改进、
    ${var@U}
    大写转换、
    ${var@L}
    小写转换
  • Bash 5.1:增强的
    ${parameter@operator}
    转换、用于兼容性的
    compat
    shopt选项
  • Bash 5.2
    varredir_close
    选项、改进的
    exec
    错误处理、
    EPOCHREALTIME
    微秒精度
  • 使用现代特性前检查版本:
    [[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]
  • 使用
    ${parameter@Q}
    生成Shell转义输出(Bash 4.4+)
  • 使用
    ${parameter@E}
    处理转义序列(Bash 4.4+)
  • 使用
    ${parameter@P}
    实现提示符扩展(Bash 4.4+)
  • 使用
    ${parameter@A}
    生成赋值格式(Bash 4.4+)
  • 借助
    wait -n
    等待任意后台任务(Bash 4.3+)
  • 使用
    mapfile -d delim
    支持自定义分隔符(Bash 4.4+)

CI/CD Integration

CI/CD集成

  • GitHub Actions: Use
    shellcheck-problem-matchers
    for inline annotations
  • Pre-commit hooks: Configure
    .pre-commit-config.yaml
    with
    shellcheck
    ,
    shfmt
    ,
    checkbashisms
  • Matrix testing: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS
  • Container testing: Use official bash:5.2 Docker images for reproducible tests
  • CodeQL: Enable shell script scanning for security vulnerabilities
  • Actionlint: Validate GitHub Actions workflow files that use shell scripts
  • Automated releases: Tag versions and generate changelogs automatically
  • Coverage reporting: Track test coverage and fail on regressions
  • Example workflow:
    shellcheck *.sh && shfmt -d *.sh && bats test/
  • GitHub Actions:使用
    shellcheck-problem-matchers
    实现内联注释
  • 预提交钩子:配置
    .pre-commit-config.yaml
    ,集成
    shellcheck
    shfmt
    checkbashisms
  • 矩阵测试:在Linux和macOS上测试Bash 4.4、5.0、5.1、5.2版本
  • 容器测试:使用官方bash:5.2 Docker镜像实现可复现测试
  • CodeQL:启用Shell脚本扫描以检测安全漏洞
  • Actionlint:验证使用Shell脚本的GitHub Actions工作流文件
  • 自动化发布:自动标记版本并生成变更日志
  • 覆盖率报告:跟踪测试覆盖率,出现回退时触发失败
  • 示例工作流:
    shellcheck *.sh && shfmt -d *.sh && bats test/

Security Scanning & Hardening

安全扫描与强化

  • SAST: Integrate Semgrep with custom rules for shell-specific vulnerabilities
  • Secrets detection: Use
    gitleaks
    or
    trufflehog
    to prevent credential leaks
  • Supply chain: Verify checksums of sourced external scripts
  • Sandboxing: Run untrusted scripts in containers with restricted privileges
  • SBOM: Document dependencies and external tools for compliance
  • Security linting: Use ShellCheck with security-focused rules enabled
  • Privilege analysis: Audit scripts for unnecessary root/sudo requirements
  • Input sanitization: Validate all external inputs against allowlists
  • Audit logging: Log all security-relevant operations to syslog
  • Container security: Scan script execution environments for vulnerabilities
  • SAST:集成Semgrep并使用自定义规则检测Shell特有的漏洞
  • 密钥检测:使用
    gitleaks
    trufflehog
    防止凭证泄露
  • 供应链安全:验证引入的外部脚本的校验和
  • 沙箱运行:在权限受限的容器中运行不可信脚本
  • SBOM:记录依赖项和外部工具以满足合规要求
  • 安全检查:启用ShellCheck的安全相关规则
  • 权限分析:审计脚本是否存在不必要的root/sudo权限要求
  • 输入清理:基于允许列表验证所有外部输入
  • 审计日志:将所有安全相关操作记录到syslog
  • 容器安全:扫描脚本执行环境的漏洞

Observability & Logging

可观测性与日志

  • Structured logging: Output JSON for log aggregation systems
  • Log levels: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity
  • Syslog integration: Use
    logger
    command for system log integration
  • Distributed tracing: Add trace IDs for multi-script workflow correlation
  • Metrics export: Output Prometheus-format metrics for monitoring
  • Error context: Include stack traces, environment info in error logs
  • Log rotation: Configure log file rotation for long-running scripts
  • Performance metrics: Track execution time, resource usage, external call latency
  • Example:
    log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }
  • 结构化日志:输出JSON格式以适配日志聚合系统
  • 日志级别:实现DEBUG、INFO、WARN、ERROR级别,并支持配置日志 verbosity
  • Syslog集成:使用
    logger
    命令集成系统日志
  • 分布式追踪:添加追踪ID以关联多脚本工作流
  • 指标导出:输出Prometheus格式的指标用于监控
  • 错误上下文:在错误日志中包含堆栈跟踪、环境信息
  • 日志轮转:为长期运行的脚本配置日志文件轮转
  • 性能指标:跟踪执行时间、资源使用情况、外部调用延迟
  • 示例:
    log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }

Quality Checklist

质量检查清单

  • Scripts pass ShellCheck static analysis with minimal suppressions
  • Code is formatted consistently with shfmt using standard options
  • Comprehensive test coverage with Bats including edge cases
  • All variable expansions are properly quoted
  • Error handling covers all failure modes with meaningful messages
  • Temporary resources are cleaned up properly with EXIT traps
  • Scripts support
    --help
    and provide clear usage information
  • Input validation prevents injection attacks and handles edge cases
  • Scripts are portable across target platforms (Linux, macOS)
  • Performance is adequate for expected workloads and data sizes
  • 脚本通过ShellCheck静态分析,仅保留最少的规则抑制
  • 代码通过shfmt使用标准选项实现一致格式化
  • 基于Bats的全面测试覆盖,包括边缘场景
  • 所有变量扩展均正确添加引号
  • 错误处理覆盖所有失败模式,并提供有意义的提示信息
  • 临时资源通过EXIT陷阱正确清理
  • 脚本支持
    --help
    并提供清晰的使用说明
  • 输入验证可防止注入攻击并处理边缘情况
  • 脚本可在目标平台(Linux、macOS)间移植
  • 性能满足预期工作负载和数据规模的要求

Output

输出成果

  • Production-ready Bash scripts with defensive programming practices
  • Comprehensive test suites using bats-core or shellspec with TAP output
  • CI/CD pipeline configurations (GitHub Actions, GitLab CI) for automated testing
  • Documentation generated with shdoc and man pages with shellman
  • Structured project layout with reusable library functions and dependency management
  • Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)
  • Performance benchmarks and profiling reports for critical workflows
  • Security review with SAST, secrets scanning, and vulnerability reports
  • Debugging utilities with trace modes, structured logging, and observability
  • Migration guides for Bash 3→5 upgrades and legacy modernization
  • Package distribution configurations (Homebrew formulas, deb/rpm specs)
  • Container images for reproducible execution environments
  • 采用防御性编程实践的生产级Bash脚本
  • 基于bats-core或shellspec的全面测试套件,输出TAP格式结果
  • 用于自动化测试的CI/CD流水线配置(GitHub Actions、GitLab CI)
  • 通过shdoc生成的文档和shellman创建的手册页
  • 包含可复用库函数和依赖管理的结构化项目布局
  • 静态分析配置文件(.shellcheckrc、.shfmt.toml、.editorconfig)
  • 关键工作流的性能基准测试与分析报告
  • 包含SAST、密钥扫描和漏洞报告的安全评审
  • 包含跟踪模式、结构化日志和可观测性的调试工具
  • Bash 3→5版本升级与遗留脚本现代化的迁移指南
  • 包分发配置(Homebrew公式、deb/rpm规格)
  • 用于可复现执行环境的容器镜像

Essential Tools

必备工具

Static Analysis & Formatting

静态分析与格式化

  • ShellCheck: Static analyzer with
    enable=all
    and
    external-sources=true
    configuration
  • shfmt: Shell script formatter with standard config (
    -i 2 -ci -bn -sr -kp
    )
  • checkbashisms: Detect bash-specific constructs for portability analysis
  • Semgrep: SAST with custom rules for shell-specific security issues
  • CodeQL: GitHub's security scanning for shell scripts
  • ShellCheck:静态分析工具,配置
    enable=all
    external-sources=true
  • shfmt:Shell脚本格式化工具,使用标准配置(
    -i 2 -ci -bn -sr -kp
  • checkbashisms:检测Bash特有语法以分析可移植性
  • Semgrep:SAST工具,使用自定义规则检测Shell特有安全问题
  • CodeQL:GitHub提供的Shell脚本安全扫描工具

Testing Frameworks

测试框架

  • bats-core: Maintained fork of Bats with modern features and active development
  • shellspec: BDD-style testing framework with rich assertions and mocking
  • shunit2: xUnit-style testing framework for shell scripts
  • bashing: Testing framework with mocking support and test isolation
  • bats-core:Bats的维护分支,具备现代特性和活跃开发
  • shellspec:BDD风格的测试框架,支持丰富的断言和模拟
  • shunit2:适用于Shell脚本的xUnit风格测试框架
  • bashing:支持模拟和测试隔离的测试框架

Modern Development Tools

现代开发工具

  • bashly: CLI framework generator for building command-line applications
  • basher: Bash package manager for dependency management
  • bpkg: Alternative bash package manager with npm-like interface
  • shdoc: Generate markdown documentation from shell script comments
  • shellman: Generate man pages from shell scripts
  • bashly:用于构建命令行应用的CLI框架生成器
  • basher:用于依赖管理的Bash包管理器
  • bpkg:类npm界面的Bash包管理器替代品
  • shdoc:从Shell脚本注释生成Markdown文档
  • shellman:从Shell脚本生成手册页

CI/CD & Automation

CI/CD与自动化

  • pre-commit: Multi-language pre-commit hook framework
  • actionlint: GitHub Actions workflow linter
  • gitleaks: Secrets scanning to prevent credential leaks
  • Makefile: Automation for lint, format, test, and release workflows
  • pre-commit:多语言预提交钩子框架
  • actionlint:GitHub Actions工作流检查工具
  • gitleaks:密钥扫描工具,防止凭证泄露
  • Makefile:用于lint、格式化、测试和发布工作流的自动化工具

Common Pitfalls to Avoid

需避免的常见陷阱

  • for f in $(ls ...)
    causing word splitting/globbing bugs (use
    find -print0 | while IFS= read -r -d '' f; do ...; done
    )
  • Unquoted variable expansions leading to unexpected behavior
  • Relying on
    set -e
    without proper error trapping in complex flows
  • Using
    echo
    for data output (prefer
    printf
    for reliability)
  • Missing cleanup traps for temporary files and directories
  • Unsafe array population (use
    readarray
    /
    mapfile
    instead of command substitution)
  • Ignoring binary-safe file handling (always consider NUL separators for filenames)
  • 使用
    for f in $(ls ...)
    导致分词/通配符匹配错误(应使用
    find -print0 | while IFS= read -r -d '' f; do ...; done
  • 未对变量添加引号导致意外行为
  • 在复杂流程中仅依赖
    set -e
    而未配置适当的错误捕获
  • 使用
    echo
    输出数据(优先使用
    printf
    以保证可靠性)
  • 未为临时文件和目录设置清理陷阱
  • 不安全的数组填充(应使用
    readarray
    /
    mapfile
    而非命令替换)
  • 忽略二进制安全的文件处理(始终考虑使用NUL分隔符处理文件名)

Dependency Management

依赖管理

  • Package managers: Use
    basher
    or
    bpkg
    for installing shell script dependencies
  • Vendoring: Copy dependencies into project for reproducible builds
  • Lock files: Document exact versions of dependencies used
  • Checksum verification: Verify integrity of sourced external scripts
  • Version pinning: Lock dependencies to specific versions to prevent breaking changes
  • Dependency isolation: Use separate directories for different dependency sets
  • Update automation: Automate dependency updates with Dependabot or Renovate
  • Security scanning: Scan dependencies for known vulnerabilities
  • Example:
    basher install username/repo@version
    or
    bpkg install username/repo -g
  • 包管理器:使用
    basher
    bpkg
    安装Shell脚本依赖
  • 依赖嵌入:将依赖项复制到项目中以实现可复现构建
  • 锁定文件:记录所使用依赖项的精确版本
  • 校验和验证:验证引入的外部脚本的完整性
  • 版本固定:将依赖项锁定到特定版本以避免破坏性变更
  • 依赖隔离:为不同的依赖集使用独立目录
  • 更新自动化:使用Dependabot或Renovate自动更新依赖
  • 安全扫描:扫描依赖项的已知漏洞
  • 示例:
    basher install username/repo@version
    bpkg install username/repo -g

Advanced Techniques

高级技巧

  • Error Context: Use
    trap 'echo "Error at line $LINENO: exit $?" >&2' ERR
    for debugging
  • Safe Temp Handling:
    trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)
  • Version Checking:
    (( BASH_VERSINFO[0] >= 5 ))
    before using modern features
  • Binary-Safe Arrays:
    readarray -d '' files < <(find . -print0)
  • Function Returns: Use
    declare -g result
    for returning complex data from functions
  • Associative Arrays:
    declare -A config=([host]="localhost" [port]="8080")
    for complex data structures
  • Parameter Expansion:
    ${filename%.sh}
    remove extension,
    ${path##*/}
    basename,
    ${text//old/new}
    replace all
  • Signal Handling:
    trap cleanup_function SIGHUP SIGINT SIGTERM
    for graceful shutdown
  • Command Grouping:
    { cmd1; cmd2; } > output.log
    share redirection,
    ( cd dir && cmd )
    use subshell for isolation
  • Co-processes:
    coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result
    for bidirectional pipes
  • Here-documents:
    cat <<-'EOF'
    with
    -
    strips leading tabs, quotes prevent expansion
  • Process Management:
    wait $pid
    to wait for background job,
    jobs -p
    list background PIDs
  • Conditional Execution:
    cmd1 && cmd2
    run cmd2 only if cmd1 succeeds,
    cmd1 || cmd2
    run cmd2 if cmd1 fails
  • Brace Expansion:
    touch file{1..10}.txt
    creates multiple files efficiently
  • Nameref Variables:
    declare -n ref=varname
    creates reference to another variable (Bash 4.3+)
  • Improved Error Trapping:
    set -Eeuo pipefail; shopt -s inherit_errexit
    for comprehensive error handling
  • Parallel Execution:
    xargs -P $(nproc) -n 1 command
    for parallel processing with CPU core count
  • Structured Output:
    jq -n --arg key "$value" '{key: $key}'
    for JSON generation
  • Performance Profiling: Use
    time -v
    for detailed resource usage or
    TIMEFORMAT
    for custom timing
  • 错误上下文:使用
    trap 'echo "Error at line $LINENO: exit $?" >&2' ERR
    进行调试
  • 安全临时文件处理
    trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)
  • 版本检查:使用
    (( BASH_VERSINFO[0] >= 5 ))
    验证是否支持现代特性
  • 二进制安全数组
    readarray -d '' files < <(find . -print0)
  • 函数返回值:使用
    declare -g result
    从函数返回复杂数据
  • 关联数组
    declare -A config=([host]="localhost" [port]="8080")
    用于存储复杂数据结构
  • 参数扩展
    ${filename%.sh}
    移除扩展名,
    ${path##*/}
    获取文件名,
    ${text//old/new}
    全局替换
  • 信号处理
    trap cleanup_function SIGHUP SIGINT SIGTERM
    实现优雅关闭
  • 命令分组
    { cmd1; cmd2; } > output.log
    共享重定向,
    ( cd dir && cmd )
    使用子shell实现隔离
  • 协同进程
    coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result
    实现双向管道
  • Here文档
    cat <<-'EOF'
    通过
    -
    去除前导制表符,引号可防止扩展
  • 进程管理
    wait $pid
    等待后台任务,
    jobs -p
    列出后台进程PID
  • 条件执行
    cmd1 && cmd2
    仅在cmd1成功时执行cmd2,
    cmd1 || cmd2
    在cmd1失败时执行cmd2
  • 大括号扩展
    touch file{1..10}.txt
    高效创建多个文件
  • 名称引用变量
    declare -n ref=varname
    创建指向其他变量的引用(Bash 4.3+)
  • 增强错误捕获
    set -Eeuo pipefail; shopt -s inherit_errexit
    实现全面错误处理
  • 并行执行
    xargs -P $(nproc) -n 1 command
    基于CPU核心数实现并行处理
  • 结构化输出
    jq -n --arg key "$value" '{key: $key}'
    生成JSON格式输出
  • 性能分析:使用
    time -v
    获取详细资源使用情况,或通过
    TIMEFORMAT
    自定义计时格式

References & Further Reading

参考资料与扩展阅读

Style Guides & Best Practices

风格指南与最佳实践

Tools & Frameworks

工具与框架

  • ShellCheck - Static analysis tool and extensive wiki documentation
  • shfmt - Shell script formatter with detailed flag documentation
  • bats-core - Maintained Bash testing framework
  • shellspec - BDD-style testing framework for shell scripts
  • bashly - Modern Bash CLI framework generator
  • shdoc - Documentation generator for shell scripts
  • ShellCheck - 静态分析工具及详尽的Wiki文档
  • shfmt - Shell脚本格式化工具,包含详细的参数文档
  • bats-core - 维护中的Bash测试框架
  • shellspec - BDD风格的Shell脚本测试框架
  • bashly - 现代Bash CLI框架生成器
  • shdoc - Shell脚本文档生成工具

Security & Advanced Topics

安全与高级主题