Use when writing production Bash scripts, CI scripts or system utilities that must fail safely: strict mode, quoting, traps and input checks. Also covers mktemp cleanup, structured logging, dry-run and idempotency.
Installs into .claude/skills of the current project.
Are you the author of Bash Defensive Patterns?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/monoes-bash-defensive-patterns)
---
name: bash-defensive-patterns
description: "Use when writing production Bash scripts, CI scripts or system utilities that must fail safely: strict mode, quoting, traps and input checks. Also covers mktemp cleanup, structured logging, dry-run and idempotency."
tags: ["devops","engineering","bash"]
tools: []
license: MIT
source: https://github.com/wshobson/agents
source_path: "plugins/shell-scripting/skills/bash-defensive-patterns"
source_commit: 4236bb91f8395b0435f1d8b8baf9e8e4c69a8620
---
# 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
1. **Always use strict mode** - `set -Eeuo pipefail`
2. **Quote all variables** - `"$variable"` prevents word splitting
3. **Use [[]] conditionals** - More robust than [ ]
4. **Implement error trapping** - Catch and handle errors gracefully
5. **Validate all inputs** - Check file existence, permissions, formats
6. **Use functions for reusability** - Prefix with meaningful names
7. **Implement structured logging** - Include timestamps and levels
8. **Support dry-run mode** - Allow users to preview changes
9. **Handle temporary files safely** - Use mktemp, cleanup with trap
10. **Design for idempotency** - Scripts should be safe to rerun
11. **Document requirements** - List dependencies and minimum versions
12. **Test error paths** - Ensure error handling works correctly
13. **Use `command -v`** - Safer than `which` for checking executables
14. **Prefer printf over echo** - More predictable across systems