1---2name: bash-pro3description: 'Master of defensive Bash scripting for production automation, CI/CD4license: MIT5---67## Use this skill when89- Writing or reviewing Bash scripts for automation, CI/CD, or ops10- Hardening shell scripts for safety and portability1112## Do not use this skill when1314- You need POSIX-only shell without Bash features15- The task requires a higher-level language for complex logic16- You need Windows-native scripting (PowerShell)1718## Instructions19201. Define script inputs, outputs, and failure modes.212. Apply strict mode and safe argument parsing.223. Implement core logic with defensive patterns.234. Add tests and linting with Bats and ShellCheck.2425## Safety2627- Treat input as untrusted; avoid eval and unsafe globbing.28- Prefer dry-run modes before destructive actions.2930## Focus Areas3132- Defensive programming with strict error handling33- POSIX compliance and cross-platform portability34- Safe argument parsing and input validation35- Robust file operations and temporary resource management36- Process orchestration and pipeline safety37- Production-grade logging and error reporting38- Comprehensive testing with Bats framework39- Static analysis with ShellCheck and formatting with shfmt40- Modern Bash 5.x features and best practices41- CI/CD integration and automation workflows4243## Approach4445- Always use strict mode with `set -Eeuo pipefail` and proper error trapping46- Quote all variable expansions to prevent word splitting and globbing issues47- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`48- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance49- Implement comprehensive argument parsing with `getopts` and usage functions50- Create temporary files and directories safely with `mktemp` and cleanup traps51- Prefer `printf` over `echo` for predictable output formatting52- Use command substitution `$()` instead of backticks for readability53- Implement structured logging with timestamps and configurable verbosity54- Design scripts to be idempotent and support dry-run modes55- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+56- Employ `IFS=$'\n\t'` to prevent unwanted word splitting on spaces57- Validate inputs with `: "${VAR:?message}"` for required environment variables58- End option parsing with `--` and use `rm -rf -- "$dir"` for safe operations59- Support `--trace` mode with `set -x` opt-in for detailed debugging60- Use `xargs -0` with NUL boundaries for safe subprocess orchestration61- Employ `readarray`/`mapfile` for safe array population from command output62- Implement robust script directory detection: `SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"`63- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`6465## Compatibility & Portability6667- Use `#!/usr/bin/env bash` shebang for portability across systems68- Check Bash version at script start: `(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))` for Bash 4.4+ features69- Validate required external commands exist: `command -v jq &>/dev/null || exit 1`70- Detect platform differences: `case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac`71- Handle GNU vs BSD tool differences (e.g., `sed -i` vs `sed -i ''`)72- Test scripts on all target platforms (Linux, macOS, BSD variants)73- Document minimum version requirements in script header comments74- Provide fallback implementations for platform-specific features75- Use built-in Bash features over external commands when possible for portability76- Avoid bashisms when POSIX compliance is required, document when using Bash-specific features7778## Readability & Maintainability7980- Use long-form options in scripts for clarity: `--verbose` instead of `-v`81- Employ consistent naming: snake_case for functions/variables, UPPER_CASE for constants82- Add section headers with comment blocks to organize related functions83- Keep functions under 50 lines; refactor larger functions into smaller components84- Group related functions together with descriptive section headers85- Use descriptive function names that explain purpose: `validate_input_file` not `check_file`86- Add inline comments for non-obvious logic, avoid stating the obvious87- Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)88- Place opening braces on same line for consistency: `function_name() {`89- Use blank lines to separate logical blocks within functions90- Document function parameters and return values in header comments91- Extract magic numbers and strings to named constants at top of script9293## Safety & Security Patterns9495- Declare constants with `readonly` to prevent accidental modification96- Use `local` keyword for all function variables to avoid polluting global scope97- Implement `timeout` for external commands: `timeout 30s curl ...` prevents hangs98- Validate file permissions before operations: `[[ -r "$file" ]] || exit 1`99- Use process substitution `<(command)` instead of temporary files when possible100- Sanitize user input before using in commands or file operations101- Validate numeric input with pattern matching: `[[ $num =~ ^[0-9]+$ ]]`102- Never use `eval` on user input; use arrays for dynamic command construction103- Set restrictive umask for sensitive operations: `(umask 077; touch "$secure_file")`104- Log security-relevant operations (authentication, privilege changes, file access)105- Use `--` to separate options from arguments: `rm -rf -- "$user_input"`106- Validate environment variables before using: `: "${REQUIRED_VAR:?not set}"`107- Check exit codes of all security-critical operations explicitly108- Use `trap` to ensure cleanup happens even on abnormal exit109110## Performance Optimization111112- Avoid subshells in loops; use `while read` instead of `for i in $(cat file)`113- Use Bash built-ins over external commands: `[[ ]]` instead of `test`, `${var//pattern/replacement}` instead of `sed`114- Batch operations instead of repeated single operations (e.g., one `sed` with multiple expressions)115- Use `mapfile`/`readarray` for efficient array population from command output116- Avoid repeated command substitutions; store result in variable once117- Use arithmetic expansion `$(( ))` instead of `expr` for calculations118- Prefer `printf` over `echo` for formatted output (faster and more reliable)119- Use associative arrays for lookups instead of repeated grepping120- Process files line-by-line for large files instead of loading entire file into memory121- Use `xargs -P` for parallel processing when operations are independent122123## Documentation Standards124125- Implement `--help` and `-h` flags showing usage, options, and examples126- Provide `--version` flag displaying script version and copyright information127- Include usage examples in help output for common use cases128- Document all command-line options with descriptions of their purpose129- List required vs optional arguments clearly in usage message130- Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures131- Include prerequisites section listing required commands and versions132- Add header comment block with script purpose, author, and modification date133- Document environment variables the script uses or requires134- Provide troubleshooting section in help for common issues135- Generate documentation with `shdoc` from special comment formats136- Create man pages using `shellman` for system integration137- Include architecture diagrams using Mermaid or GraphViz for complex scripts138139## Modern Bash Features (5.x)140141- **Bash 5.0**: Associative array improvements, `${var@U}` uppercase conversion, `${var@L}` lowercase142- **Bash 5.1**: Enhanced `${parameter@operator}` transformations, `compat` shopt options for compatibility143- **Bash 5.2**: `varredir_close` option, improved `exec` error handling, `EPOCHREALTIME` microsecond precision144- Check version before using modern features: `[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]`145- Use `${parameter@Q}` for shell-quoted output (Bash 4.4+)146- Use `${parameter@E}` for escape sequence expansion (Bash 4.4+)147- Use `${parameter@P}` for prompt expansion (Bash 4.4+)148- Use `${parameter@A}` for assignment format (Bash 4.4+)149- Employ `wait -n` to wait for any background job (Bash 4.3+)150- Use `mapfile -d delim` for custom delimiters (Bash 4.4+)151152## CI/CD Integration153154- **GitHub Actions**: Use `shellcheck-problem-matchers` for inline annotations155- **Pre-commit hooks**: Configure `.pre-commit-config.yaml` with `shellcheck`, `shfmt`, `checkbashisms`156- **Matrix testing**: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS157- **Container testing**: Use official bash:5.2 Docker images for reproducible tests158- **CodeQL**: Enable shell script scanning for security vulnerabilities159- **Actionlint**: Validate GitHub Actions workflow files that use shell scripts160- **Automated releases**: Tag versions and generate changelogs automatically161- **Coverage reporting**: Track test coverage and fail on regressions162- Example workflow: `shellcheck *.sh && shfmt -d *.sh && bats test/`163164## Security Scanning & Hardening165166- **SAST**: Integrate Semgrep with custom rules for shell-specific vulnerabilities167- **Secrets detection**: Use `gitleaks` or `trufflehog` to prevent credential leaks168- **Supply chain**: Verify checksums of sourced external scripts169- **Sandboxing**: Run untrusted scripts in containers with restricted privileges170- **SBOM**: Document dependencies and external tools for compliance171- **Security linting**: Use ShellCheck with security-focused rules enabled172- **Privilege analysis**: Audit scripts for unnecessary root/sudo requirements173- **Input sanitization**: Validate all external inputs against allowlists174- **Audit logging**: Log all security-relevant operations to syslog175- **Container security**: Scan script execution environments for vulnerabilities176177## Observability & Logging178179- **Structured logging**: Output JSON for log aggregation systems180- **Log levels**: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity181- **Syslog integration**: Use `logger` command for system log integration182- **Distributed tracing**: Add trace IDs for multi-script workflow correlation183- **Metrics export**: Output Prometheus-format metrics for monitoring184- **Error context**: Include stack traces, environment info in error logs185- **Log rotation**: Configure log file rotation for long-running scripts186- **Performance metrics**: Track execution time, resource usage, external call latency187- Example: `log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }`188189## Quality Checklist190191- Scripts pass ShellCheck static analysis with minimal suppressions192- Code is formatted consistently with shfmt using standard options193- Comprehensive test coverage with Bats including edge cases194- All variable expansions are properly quoted195- Error handling covers all failure modes with meaningful messages196- Temporary resources are cleaned up properly with EXIT traps197- Scripts support `--help` and provide clear usage information198- Input validation prevents injection attacks and handles edge cases199- Scripts are portable across target platforms (Linux, macOS)200- Performance is adequate for expected workloads and data sizes201202## Output203204- Production-ready Bash scripts with defensive programming practices205- Comprehensive test suites using bats-core or shellspec with TAP output206- CI/CD pipeline configurations (GitHub Actions, GitLab CI) for automated testing207- Documentation generated with shdoc and man pages with shellman208- Structured project layout with reusable library functions and dependency management209- Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)210- Performance benchmarks and profiling reports for critical workflows211- Security review with SAST, secrets scanning, and vulnerability reports212- Debugging utilities with trace modes, structured logging, and observability213- Migration guides for Bash 3→5 upgrades and legacy modernization214- Package distribution configurations (Homebrew formulas, deb/rpm specs)215- Container images for reproducible execution environments216217## Essential Tools218219### Static Analysis & Formatting220- **ShellCheck**: Static analyzer with `enable=all` and `external-sources=true` configuration221- **shfmt**: Shell script formatter with standard config (`-i 2 -ci -bn -sr -kp`)222- **checkbashisms**: Detect bash-specific constructs for portability analysis223- **Semgrep**: SAST with custom rules for shell-specific security issues224- **CodeQL**: GitHub's security scanning for shell scripts225226### Testing Frameworks227- **bats-core**: Maintained fork of Bats with modern features and active development228- **shellspec**: BDD-style testing framework with rich assertions and mocking229- **shunit2**: xUnit-style testing framework for shell scripts230- **bashing**: Testing framework with mocking support and test isolation231232### Modern Development Tools233- **bashly**: CLI framework generator for building command-line applications234- **basher**: Bash package manager for dependency management235- **bpkg**: Alternative bash package manager with npm-like interface236- **shdoc**: Generate markdown documentation from shell script comments237- **shellman**: Generate man pages from shell scripts238239### CI/CD & Automation240- **pre-commit**: Multi-language pre-commit hook framework241- **actionlint**: GitHub Actions workflow linter242- **gitleaks**: Secrets scanning to prevent credential leaks243- **Makefile**: Automation for lint, format, test, and release workflows244245## Common Pitfalls to Avoid246247- `for f in $(ls ...)` causing word splitting/globbing bugs (use `find -print0 | while IFS= read -r -d '' f; do ...; done`)248- Unquoted variable expansions leading to unexpected behavior249- Relying on `set -e` without proper error trapping in complex flows250- Using `echo` for data output (prefer `printf` for reliability)251- Missing cleanup traps for temporary files and directories252- Unsafe array population (use `readarray`/`mapfile` instead of command substitution)253- Ignoring binary-safe file handling (always consider NUL separators for filenames)254255## Dependency Management256257- **Package managers**: Use `basher` or `bpkg` for installing shell script dependencies258- **Vendoring**: Copy dependencies into project for reproducible builds259- **Lock files**: Document exact versions of dependencies used260- **Checksum verification**: Verify integrity of sourced external scripts261- **Version pinning**: Lock dependencies to specific versions to prevent breaking changes262- **Dependency isolation**: Use separate directories for different dependency sets263- **Update automation**: Automate dependency updates with Dependabot or Renovate264- **Security scanning**: Scan dependencies for known vulnerabilities265- Example: `basher install username/repo@version` or `bpkg install username/repo -g`266267## Advanced Techniques268269- **Error Context**: Use `trap 'echo "Error at line $LINENO: exit $?" >&2' ERR` for debugging270- **Safe Temp Handling**: `trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)`271- **Version Checking**: `(( BASH_VERSINFO[0] >= 5 ))` before using modern features272- **Binary-Safe Arrays**: `readarray -d '' files < <(find . -print0)`273- **Function Returns**: Use `declare -g result` for returning complex data from functions274- **Associative Arrays**: `declare -A config=([host]="localhost" [port]="8080")` for complex data structures275- **Parameter Expansion**: `${filename%.sh}` remove extension, `${path##*/}` basename, `${text//old/new}` replace all276- **Signal Handling**: `trap cleanup_function SIGHUP SIGINT SIGTERM` for graceful shutdown277- **Command Grouping**: `{ cmd1; cmd2; } > output.log` share redirection, `( cd dir && cmd )` use subshell for isolation278- **Co-processes**: `coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result` for bidirectional pipes279- **Here-documents**: `cat <<-'EOF'` with `-` strips leading tabs, quotes prevent expansion280- **Process Management**: `wait $pid` to wait for background job, `jobs -p` list background PIDs281- **Conditional Execution**: `cmd1 && cmd2` run cmd2 only if cmd1 succeeds, `cmd1 || cmd2` run cmd2 if cmd1 fails282- **Brace Expansion**: `touch file{1..10}.txt` creates multiple files efficiently283- **Nameref Variables**: `declare -n ref=varname` creates reference to another variable (Bash 4.3+)284- **Improved Error Trapping**: `set -Eeuo pipefail; shopt -s inherit_errexit` for comprehensive error handling285- **Parallel Execution**: `xargs -P $(nproc) -n 1 command` for parallel processing with CPU core count286- **Structured Output**: `jq -n --arg key "$value" '{key: $key}'` for JSON generation287- **Performance Profiling**: Use `time -v` for detailed resource usage or `TIMEFORMAT` for custom timing288289## References & Further Reading290291### Style Guides & Best Practices292- [Google Shell Style Guide](https://google.github.io/styleguide/shellguide.html) - Comprehensive style guide covering quoting, arrays, and when to use shell293- [Bash Pitfalls](https://mywiki.wooledge.org/BashPitfalls) - Catalog of common Bash mistakes and how to avoid them294- [Bash Hackers Wiki](https://wiki.bash-hackers.org/) - Comprehensive Bash documentation and advanced techniques295- [Defensive BASH Programming](https://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) - Modern defensive programming patterns296297### Tools & Frameworks298- [ShellCheck](https://github.com/koalaman/shellcheck) - Static analysis tool and extensive wiki documentation299- [shfmt](https://github.com/mvdan/sh) - Shell script formatter with detailed flag documentation300- [bats-core](https://github.com/bats-core/bats-core) - Maintained Bash testing framework301- [shellspec](https://github.com/shellspec/shellspec) - BDD-style testing framework for shell scripts302- [bashly](https://bashly.dannyb.co/) - Modern Bash CLI framework generator303- [shdoc](https://github.com/reconquest/shdoc) - Documentation generator for shell scripts304305### Security & Advanced Topics306- [Bash Security Best Practices](https://github.com/carlospolop/PEASS-ng) - Security-focused shell script patterns307- [Awesome Bash](https://github.com/awesome-lists/awesome-bash) - Curated list of Bash resources and tools308- [Pure Bash Bible](https://github.com/dylanaraps/pure-bash-bible) - Collection of pure bash alternatives to external commands309310## Limitations311- Use this skill only when the task clearly matches the scope described above.312- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.313- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.