bash-defensive-patterns
它能做什么
这份指南教你如何编写更安全、更可靠的自动化脚本(Bash)。它能帮你避免常见错误,并确保脚本即使在意外情况下也能正确运行。
适用场景
- ✓编写用于自动化重要工作任务的脚本时。
- ✓为开发流程(CI/CD)搭建自动化步骤时。
- ✓开发需要高度可靠性的系统工具时。
技能链接
https://github.com/wshobson/agents/blob/main/plugins/shell-scripting/skills/bash-defensive-patterns/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“怎样编写一个 Bash 脚本,使其在文件不存在时不会失败?”
每周 5 个新技能,1 分钟读完。
工作原理
它会使用一些技巧,例如开启安全模式(`set -euo pipefail`)、始终用引号保护变量(`"$variable"`),以及检查命令是否成功执行。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Bash Defensive Patterns
Comprehensive guidance for writing production-ready Bash scripts using defensive programming techniques, error handling, and safety best practices to prevent common pitfalls and ensure reliability.
When to Use This Skill
- Writing production automation scripts
- Building CI/CD pipeline scripts
- Creating system administration utilities
- Developing error-resilient deployment automation
- Writing scripts that must handle edge cases safely
- Building maintainable shell script libraries
- Implementing comprehensive logging and monitoring
- Creating scripts that must work across different platforms
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
Best Practices Summary
- Always use strict mode -
set -Eeuo pipefail - Quote all variables -
"$variable"prevents word splitting - Use [[]] conditionals - More robust than [ ]
- Implement error trapping - Catch and handle errors gracefully
- Validate all inputs - Check file existence, permissions, formats
- Use functions for reusability - Prefix with meaningful names
- Implement structured logging - Include timestamps and levels
- Support dry-run mode - Allow users to preview changes
- Handle temporary files safely - Use mktemp, cleanup with trap
- Design for idempotency - Scripts should be safe to rerun
- Document requirements - List dependencies and minimum versions
- Test error paths - Ensure error handling works correctly
- Use
command -v- Safer thanwhichfor checking executables - Prefer printf over echo - More predictable across systems
常见问题
什么是“严格模式”?
它是一组规则(`set -Eeuo pipefail`),能让脚本运行得更严谨,迫使你修正那些原本可能被忽略的常见错误。
为什么要给变量加引号?
给变量加上引号(`"$variable"`)可以防止脚本误解变量值中的空格或特殊字符,从而避免出错。
“幂等性”是什么意思?
幂等的脚本可以多次运行而不会产生意外的副作用,无论执行多少次,最终结果都相同。
详情
作者的原始描述
Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI/CD pipelines, or system utilities requiring fault tolerance and safety.
repo: wshobson/agents
热度
- GitHub 星标
- 41k
- 排名
- #6783
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …