1---2version: 4.1.0-fractal3name: bash-pro4description: Master of defensive Bash scripting for production automation, CI/CD5 pipelines, and system utilities. Expert in safe, portable, and testable shell6 scripts.7metadata:8 source: https://skillmd.com/skills/dokhacgiakhoa/bash-pro9 model: sonnet10---1112## Use this skill when1314- Writing or reviewing Bash scripts for automation, CI/CD, or ops15- Hardening shell scripts for safety and portability1617## Do not use this skill when1819- You need POSIX-only shell without Bash features20- The task requires a higher-level language for complex logic21- You need Windows-native scripting (PowerShell)2223## Instructions24251. Define script inputs, outputs, and failure modes.262. Apply strict mode and safe argument parsing.273. Implement core logic with defensive patterns.284. Add tests and linting with Bats and ShellCheck.2930## Safety3132- Treat input as untrusted; avoid eval and unsafe globbing.33- Prefer dry-run modes before destructive actions.3435## Focus Areas3637- Defensive programming with strict error handling38- POSIX compliance and cross-platform portability39- Safe argument parsing and input validation40- Robust file operations and temporary resource management41- Process orchestration and pipeline safety42- Production-grade logging and error reporting43- Comprehensive testing with Bats framework44- Static analysis with ShellCheck and formatting with shfmt45- Modern Bash 5.x features and best practices46- CI/CD integration and automation workflows4748## Approach4950- Always use strict mode with `set -Eeuo pipefail` and proper error trapping51- Quote all variable expansions to prevent word splitting and globbing issues52- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`53- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance54- Implement comprehensive argument parsing with `getopts` and usage functions55- Create temporary files and directories safely with `mktemp` and cleanup traps56- Prefer `printf` over `echo` for predictable output formatting57- Use command substitution `$()` instead of backticks for readability58- Implement structured logging with timestamps and configurable verbosity59- Design scripts to be idempotent and support dry-run modes60- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+61- Employ `IFS=$'\n\t'` to prevent unwanted word splitting on spaces62- Validate inputs with `: "${VAR:?message}"` for required environment variables63- End option parsing with `--` and use `rm -rf -- "$dir"` for safe operations64- Support `--trace` mode with `set -x` opt-in for detailed debugging65- Use `xargs -0` with NUL boundaries for safe subprocess orchestration66- Employ `readarray`/`mapfile` for safe array population from command output67- Implement robust script directory detection: `SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"`68- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`6970## Compatibility & Portability7172- Use `#!/usr/bin/env bash` shebang for portability across systems73- Check Bash version at script start: `(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))` for Bash 4.4+ features74- Validate required external commands exist: `command -v jq &>/dev/null || exit 1`75- Detect platform differences: `case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac`76- Handle GNU vs BSD tool differences (e.g., `sed -i` vs `sed -i ''`)77- Test scripts on all target platforms (Linux, macOS, BSD variants)78- Document minimum version requirements in script header comments79- Provide fallback implementations for platform-specific features80- Use built-in Bash features over external commands when possible for portability81- Avoid bashisms when POSIX compliance is required, document when using Bash-specific features8283## Readability & Maintainability8485- Use long-form options in scripts for clarity: `--verbose` instead of `-v`86- Employ consistent naming: snake_case for functions/variables, UPPER_CASE for constants87- Add section headers with comment blocks to organize related functions88- Keep functions under 50 lines; refactor larger functions into smaller components89- Group related functions together with descriptive section headers90- Use descriptive function names that explain purpose: `validate_input_file` not `check_file`91- Add inline comments for non-obvious logic, avoid stating the obvious92- Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)93- Place opening braces on same line for consistency: `function_name() {`94- Use blank lines to separate logical blocks within functions95- Document function parameters and return values in header comments96- Extract magic numbers and strings to named constants at top of script9798## Safety & Security Patterns99100- Declare constants with `readonly` to prevent accidental modification101- Use `local` keyword for all function variables to avoid polluting global scope102- Implement `timeout` for external commands: `timeout 30s curl ...` prevents hangs103- Validate file permissions before operations: `[[ -r "$file" ]] || exit 1`104- Use process substitution `<(command)` instead of temporary files when possible105- Sanitize user input before using in commands or file operations106- Validate numeric input with pattern matching: `[[ $num =~ ^[0-9]+$ ]]`107- Never use `eval` on user input; use arrays for dynamic command construction108- Set restrictive umask for sensitive operations: `(umask 077; touch "$secure_file")`109- Log security-relevant operations (authentication, privilege changes, file access)110- Use `--` to separate options from arguments: `rm -rf -- "$user_input"`111- Validate environment variables before using: `: "${REQUIRED_VAR:?not set}"`112- Check exit codes of all security-critical operations explicitly113- Use `trap` to ensure cleanup happens even on abnormal exit114115## Performance Optimization116117- Avoid subshells in loops; use `while read` instead of `for i in $(cat file)`118- Use Bash built-ins over external commands: `[[ ]]` instead of `test`, `${var//pattern/replacement}` instead of `sed`119- Batch operations instead of repeated single operations (e.g., one `sed` with multiple expressions)120- Use `mapfile`/`readarray` for efficient array population from command output121- Avoid repeated command substitutions; store result in variable once122- Use arithmetic expansion `$(( ))` instead of `expr` for calculations123- Prefer `printf` over `echo` for formatted output (faster and more reliable)124- Use associative arrays for lookups instead of repeated grepping125- Process files line-by-line for large files instead of loading entire file into memory126- Use `xargs -P` for parallel processing when operations are independent127128## Documentation Standards129130- Implement `--help` and `-h` flags showing usage, options, and examples131- Provide `--version` flag displaying script version and copyright information132- Include usage examples in help output for common use cases133- Document all command-line options with descriptions of their purpose134- List required vs optional arguments clearly in usage message135- Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures136- Include prerequisites section listing required commands and versions137- Add header comment block with script purpose, author, and modification date138- Document environment variables the script uses or requires139- Provide troubleshooting section in help for common issues140- Generate documentation with `shdoc` from special comment formats141- Create man pages using `shellman` for system integration142- Include architecture diagrams using Mermaid or GraphViz for complex scripts143144## Modern Bash Features (5.x)145146- **Bash 5.0**: Associative array improvements, `${var@U}` uppercase conversion, `${var@L}` lowercase147- **Bash 5.1**: Enhanced `${parameter@operator}` transformations, `compat` shopt options for compatibility148- **Bash 5.2**: `varredir_close` option, improved `exec` error handling, `EPOCHREALTIME` microsecond precision149- Check version before using modern features: `[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]`150- Use `${parameter@Q}` for shell-quoted output (Bash 4.4+)151- Use `${parameter@E}` for escape sequence expansion (Bash 4.4+)152- Use `${parameter@P}` for prompt expansion (Bash 4.4+)153- Use `${parameter@A}` for assignment format (Bash 4.4+)154- Employ `wait -n` to wait for any background job (Bash 4.3+)155- Use `mapfile -d delim` for custom delimiters (Bash 4.4+)156157## CI/CD Integration158159- **GitHub Actions**: Use `shellcheck-problem-matchers` for inline annotations160- **Pre-commit hooks**: Configure `.pre-commit-config.yaml` with `shellcheck`, `shfmt`, `checkbashisms`161- **Matrix testing**: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS162- **Container testing**: Use official bash:5.2 Docker images for reproducible tests163- **CodeQL**: Enable shell script scanning for security vulnerabilities164- **Actionlint**: Validate GitHub Actions workflow files that use shell scripts165- **Automated releases**: Tag versions and generate changelogs automatically166- **Coverage reporting**: Track test coverage and fail on regressions167- Example workflow: `shellcheck *.sh && shfmt -d *.sh && bats test/`168169## Security Scanning & Hardening170171- **SAST**: Integrate Semgrep with custom rules for shell-specific vulnerabilities172- **Secrets detection**: Use `gitleaks` or `trufflehog` to prevent credential leaks173- **Supply chain**: Verify checksums of sourced external scripts174- **Sandboxing**: Run untrusted scripts in containers with restricted privileges175- **SBOM**: Document dependencies and external tools for compliance176- **Security linting**: Use ShellCheck with security-focused rules enabled177- **Privilege analysis**: Audit scripts for unnecessary root/sudo requirements178- **Input sanitization**: Validate all external inputs against allowlists179- **Audit logging**: Log all security-relevant operations to syslog180- **Container security**: Scan script execution environments for vulnerabilities181182## Observability & Logging183184- **Structured logging**: Output JSON for log aggregation systems185- **Log levels**: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity186- **Syslog integration**: Use `logger` command for system log integration187- **Distributed tracing**: Add trace IDs for multi-script workflow correlation188- **Metrics export**: Output Prometheus-format metrics for monitoring189- **Error context**: Include stack traces, environment info in error logs190- **Log rotation**: Configure log file rotation for long-running scripts191- **Performance metrics**: Track execution time, resource usage, external call latency192- Example: `log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }`193194## Quality Checklist195196- Scripts pass ShellCheck static analysis with minimal suppressions197- Code is formatted consistently with shfmt using standard options198- Comprehensive test coverage with Bats including edge cases199- All variable expansions are properly quoted200- Error handling covers all failure modes with meaningful messages201- Temporary resources are cleaned up properly with EXIT traps202- Scripts support `--help` and provide clear usage information203- Input validation prevents injection attacks and handles edge cases204- Scripts are portable across target platforms (Linux, macOS)205- Performance is adequate for expected workloads and data sizes206207## Output208209- Production-ready Bash scripts with defensive programming practices210- Comprehensive test suites using bats-core or shellspec with TAP output211- CI/CD pipeline configurations (GitHub Actions, GitLab CI) for automated testing212- Documentation generated with shdoc and man pages with shellman213- Structured project layout with reusable library functions and dependency management214- Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)215- Performance benchmarks and profiling reports for critical workflows216- Security review with SAST, secrets scanning, and vulnerability reports217- Debugging utilities with trace modes, structured logging, and observability218- Migration guides for Bash 3→5 upgrades and legacy modernization219- Package distribution configurations (Homebrew formulas, deb/rpm specs)220- Container images for reproducible execution environments221222## Essential Tools223224## 🧠 Knowledge Modules (Fractal Skills)225226### 1. [Static Analysis & Formatting](./sub-skills/static-analysis-formatting.md)227### 2. [Testing Frameworks](./sub-skills/testing-frameworks.md)228### 3. [Modern Development Tools](./sub-skills/modern-development-tools.md)229### 4. [CI/CD & Automation](./sub-skills/cicd-automation.md)230### 5. [Style Guides & Best Practices](./sub-skills/style-guides-best-practices.md)231### 6. [Tools & Frameworks](./sub-skills/tools-frameworks.md)232### 7. [Security & Advanced Topics](./sub-skills/security-advanced-topics.md)