bash-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUse 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
操作指南
- Define script inputs, outputs, and failure modes.
- Apply strict mode and safe argument parsing.
- Implement core logic with defensive patterns.
- Add tests and linting with Bats and ShellCheck.
- 定义脚本的输入、输出和失败模式。
- 应用严格模式和安全的参数解析。
- 使用防御性模式实现核心逻辑。
- 通过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 and proper error trapping
set -Eeuo pipefail - 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 and usage functions
getopts - Create temporary files and directories safely with and cleanup traps
mktemp - Prefer over
printffor predictable output formattingecho - 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 for better error propagation in Bash 4.4+
shopt -s inherit_errexit - Employ to prevent unwanted word splitting on spaces
IFS=$'\n\t' - Validate inputs with for required environment variables
: "${VAR:?message}" - End option parsing with and use
--for safe operationsrm -rf -- "$dir" - Support mode with
--traceopt-in for detailed debuggingset -x - Use with NUL boundaries for safe subprocess orchestration
xargs -0 - Employ /
readarrayfor safe array population from command outputmapfile - 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 - 使用结合NUL分隔符实现安全的子流程编排
xargs -0 - 借助/
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 shebang for portability across systems
#!/usr/bin/env bash - Check Bash version at script start: for Bash 4.4+ features
(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 )) - 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., vs
sed -i)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
- 使用shebang以实现跨系统可移植性
#!/usr/bin/env bash - 脚本启动时检查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工具差异(如vs
sed -i)sed -i '' - 在所有目标平台(Linux、macOS、BSD变体)上测试脚本
- 在脚本头部注释中记录最低版本要求
- 为平台特定特性提供回退实现
- 为提升可移植性,优先使用Bash内置功能而非外部命令
- 若需POSIX合规则避免Bash特有语法,使用Bash专属特性时需注明
Readability & Maintainability
可读性与可维护性
- Use long-form options in scripts for clarity: instead of
--verbose-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: not
validate_input_filecheck_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_filecheck_file - 为非显而易见的逻辑添加行内注释,避免陈述显而易见的内容
- 保持一致的缩进(2或4个空格,禁止混合使用制表符和空格)
- 保持大括号与函数名同行:
function_name() { - 使用空行分隔函数内的逻辑块
- 在函数头部注释中记录参数与返回值
- 将魔法数字和字符串提取为脚本顶部的命名常量
Safety & Security Patterns
安全与安全模式
- Declare constants with to prevent accidental modification
readonly - Use keyword for all function variables to avoid polluting global scope
local - Implement for external commands:
timeoutprevents hangstimeout 30s curl ... - Validate file permissions before operations:
[[ -r "$file" ]] || exit 1 - Use process substitution instead of temporary files when possible
<(command) - Sanitize user input before using in commands or file operations
- Validate numeric input with pattern matching:
[[ $num =~ ^[0-9]+$ ]] - Never use on user input; use arrays for dynamic command construction
eval - 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 to ensure cleanup happens even on abnormal exit
trap
- 使用声明常量,防止意外修改
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 instead of
while readfor i in $(cat file) - Use Bash built-ins over external commands: instead of
[[ ]],testinstead of${var//pattern/replacement}sed - Batch operations instead of repeated single operations (e.g., one with multiple expressions)
sed - Use /
mapfilefor efficient array population from command outputreadarray - Avoid repeated command substitutions; store result in variable once
- Use arithmetic expansion instead of
$(( ))for calculationsexpr - Prefer over
printffor formatted output (faster and more reliable)echo - 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 for parallel processing when operations are independent
xargs -P
- 避免在循环中使用子shell;使用而非
while readfor i in $(cat file) - 优先使用Bash内置功能而非外部命令:如而非
[[ ]],test而非${var//pattern/replacement}sed - 批量操作替代重复的单次操作(如一个命令包含多个表达式)
sed - 使用/
mapfile高效从命令输出填充数组readarray - 避免重复的命令替换;将结果存储到变量中复用
- 使用算术扩展而非
$(( ))进行计算expr - 优先使用而非
printf生成格式化输出(更快更可靠)echo - 使用关联数组实现查找,替代重复的grep操作
- 处理大文件时逐行读取,而非将整个文件加载到内存
- 操作相互独立时,使用实现并行处理
xargs -P
Documentation Standards
文档规范
- Implement and
--helpflags showing usage, options, and examples-h - Provide flag displaying script version and copyright information
--version - 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 from special comment formats
shdoc - Create man pages using for system integration
shellman - 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, uppercase conversion,
${var@U}lowercase${var@L} - Bash 5.1: Enhanced transformations,
${parameter@operator}shopt options for compatibilitycompat - Bash 5.2: option, improved
varredir_closeerror handling,execmicrosecond precisionEPOCHREALTIME - Check version before using modern features:
[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]] - Use for shell-quoted output (Bash 4.4+)
${parameter@Q} - Use for escape sequence expansion (Bash 4.4+)
${parameter@E} - Use for prompt expansion (Bash 4.4+)
${parameter@P} - Use for assignment format (Bash 4.4+)
${parameter@A} - Employ to wait for any background job (Bash 4.3+)
wait -n - Use for custom delimiters (Bash 4.4+)
mapfile -d delim
- Bash 5.0:关联数组改进、大写转换、
${var@U}小写转换${var@L} - Bash 5.1:增强的转换、用于兼容性的
${parameter@operator}shopt选项compat - Bash 5.2:选项、改进的
varredir_close错误处理、exec微秒精度EPOCHREALTIME - 使用现代特性前检查版本:
[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]] - 使用生成Shell转义输出(Bash 4.4+)
${parameter@Q} - 使用处理转义序列(Bash 4.4+)
${parameter@E} - 使用实现提示符扩展(Bash 4.4+)
${parameter@P} - 使用生成赋值格式(Bash 4.4+)
${parameter@A} - 借助等待任意后台任务(Bash 4.3+)
wait -n - 使用支持自定义分隔符(Bash 4.4+)
mapfile -d delim
CI/CD Integration
CI/CD集成
- GitHub Actions: Use for inline annotations
shellcheck-problem-matchers - Pre-commit hooks: Configure with
.pre-commit-config.yaml,shellcheck,shfmtcheckbashisms - 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、shfmtcheckbashisms - 矩阵测试:在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 or
gitleaksto prevent credential leakstrufflehog - 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 command for system log integration
logger - 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 and provide clear usage information
--help - 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 and
enable=allconfigurationexternal-sources=true - 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=allexternal-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
需避免的常见陷阱
- causing word splitting/globbing bugs (use
for f in $(ls ...))find -print0 | while IFS= read -r -d '' f; do ...; done - Unquoted variable expansions leading to unexpected behavior
- Relying on without proper error trapping in complex flows
set -e - Using for data output (prefer
echofor reliability)printf - Missing cleanup traps for temporary files and directories
- Unsafe array population (use /
readarrayinstead of command substitution)mapfile - 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 or
basherfor installing shell script dependenciesbpkg - 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: or
basher install username/repo@versionbpkg install username/repo -g
- 包管理器:使用或
basher安装Shell脚本依赖bpkg - 依赖嵌入:将依赖项复制到项目中以实现可复现构建
- 锁定文件:记录所使用依赖项的精确版本
- 校验和验证:验证引入的外部脚本的完整性
- 版本固定:将依赖项锁定到特定版本以避免破坏性变更
- 依赖隔离:为不同的依赖集使用独立目录
- 更新自动化:使用Dependabot或Renovate自动更新依赖
- 安全扫描:扫描依赖项的已知漏洞
- 示例:或
basher install username/repo@versionbpkg install username/repo -g
Advanced Techniques
高级技巧
- Error Context: Use for debugging
trap 'echo "Error at line $LINENO: exit $?" >&2' ERR - Safe Temp Handling:
trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d) - Version Checking: before using modern features
(( BASH_VERSINFO[0] >= 5 )) - Binary-Safe Arrays:
readarray -d '' files < <(find . -print0) - Function Returns: Use for returning complex data from functions
declare -g result - Associative Arrays: for complex data structures
declare -A config=([host]="localhost" [port]="8080") - Parameter Expansion: remove extension,
${filename%.sh}basename,${path##*/}replace all${text//old/new} - Signal Handling: for graceful shutdown
trap cleanup_function SIGHUP SIGINT SIGTERM - Command Grouping: share redirection,
{ cmd1; cmd2; } > output.loguse subshell for isolation( cd dir && cmd ) - Co-processes: for bidirectional pipes
coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result - Here-documents: with
cat <<-'EOF'strips leading tabs, quotes prevent expansion- - Process Management: to wait for background job,
wait $pidlist background PIDsjobs -p - Conditional Execution: run cmd2 only if cmd1 succeeds,
cmd1 && cmd2run cmd2 if cmd1 failscmd1 || cmd2 - Brace Expansion: creates multiple files efficiently
touch file{1..10}.txt - Nameref Variables: creates reference to another variable (Bash 4.3+)
declare -n ref=varname - Improved Error Trapping: for comprehensive error handling
set -Eeuo pipefail; shopt -s inherit_errexit - Parallel Execution: for parallel processing with CPU core count
xargs -P $(nproc) -n 1 command - Structured Output: for JSON generation
jq -n --arg key "$value" '{key: $key}' - Performance Profiling: Use for detailed resource usage or
time -vfor custom timingTIMEFORMAT
- 错误上下文:使用进行调试
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使用子shell实现隔离( cd dir && cmd ) - 协同进程:实现双向管道
coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result - Here文档:通过
cat <<-'EOF'去除前导制表符,引号可防止扩展- - 进程管理:等待后台任务,
wait $pid列出后台进程PIDjobs -p - 条件执行:仅在cmd1成功时执行cmd2,
cmd1 && cmd2在cmd1失败时执行cmd2cmd1 || cmd2 - 大括号扩展:高效创建多个文件
touch file{1..10}.txt - 名称引用变量:创建指向其他变量的引用(Bash 4.3+)
declare -n ref=varname - 增强错误捕获:实现全面错误处理
set -Eeuo pipefail; shopt -s inherit_errexit - 并行执行:基于CPU核心数实现并行处理
xargs -P $(nproc) -n 1 command - 结构化输出:生成JSON格式输出
jq -n --arg key "$value" '{key: $key}' - 性能分析:使用获取详细资源使用情况,或通过
time -v自定义计时格式TIMEFORMAT
References & Further Reading
参考资料与扩展阅读
Style Guides & Best Practices
风格指南与最佳实践
- Google Shell Style Guide - Comprehensive style guide covering quoting, arrays, and when to use shell
- Bash Pitfalls - Catalog of common Bash mistakes and how to avoid them
- Bash Hackers Wiki - Comprehensive Bash documentation and advanced techniques
- Defensive BASH Programming - Modern defensive programming patterns
- Google Shell Style Guide - 涵盖引号使用、数组和Shell适用场景的全面风格指南
- Bash Pitfalls - 常见Bash错误汇总及规避方法
- Bash Hackers Wiki - 全面的Bash文档与高级技巧
- Defensive BASH Programming - 现代防御性编程模式
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
Security & Advanced Topics
安全与高级主题
- Bash Security Best Practices - Security-focused shell script patterns
- Awesome Bash - Curated list of Bash resources and tools
- Pure Bash Bible - Collection of pure bash alternatives to external commands
- Bash Security Best Practices - 聚焦安全的Shell脚本模式
- Awesome Bash - 精选Bash资源与工具列表
- Pure Bash Bible - 纯Bash实现替代外部命令的集合