1---2name: bash-pro3description: Use this skill when4---56## Use this skill when78- Writing or reviewing Bash scripts for automation, CI/CD, or ops9- Hardening shell scripts for safety and portability1011## Do not use this skill when1213- You need POSIX-only shell without Bash features14- The task requires a higher-level language for complex logic15- You need Windows-native scripting (PowerShell)1617## Instructions18191. Define script inputs, outputs, and failure modes.202. Apply strict mode and safe argument parsing.213. Implement core logic with defensive patterns.224. Add tests and linting with Bats and ShellCheck.2324## Safety2526- Treat input as untrusted; avoid eval and unsafe globbing.27- Prefer dry-run modes before destructive actions.2829## Focus Areas3031- Defensive programming with strict error handling32- POSIX compliance and cross-platform portability33- Safe argument parsing and input validation34- Robust file operations and temporary resource management35- Process orchestration and pipeline safety36- Production-grade logging and error reporting37- Comprehensive testing with Bats framework38- Static analysis with ShellCheck and formatting with shfmt39- Modern Bash 5.x features and best practices40- CI/CD integration and automation workflows4142## Approach4344- Always use strict mode with `set -Eeuo pipefail` and proper error trapping45- Quote all variable expansions to prevent word splitting and globbing issues46- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`47- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance48- Implement comprehensive argument parsing with `getopts` and usage functions49- Create temporary files and directories safely with `mktemp` and cleanup traps50- Prefer `printf` over `echo` for predictable output formatting51- Use command substitution `$()` instead of backticks for readability52- Implement structured logging with timestamps and configurable verbosity53- Design scripts to be idempotent and support dry-run modes54- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+55- Employ `IFS=$'\n\t'` to prevent unwanted word splitting on spaces56- Validate inputs with `: "${VAR:?message}"` for required environment variables57- End option parsing with `--` and use `rm -rf -- "$dir"` for safe operations58- Support `--trace` mode with `set -x` opt-in for detailed debugging59- Use `xargs -0` with NUL boundaries for safe subprocess orchestration60- Employ `readarray`/`mapfile` for safe array population from command output61- Implement robust script directory detection: `SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"`62- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`6364## Compatibility & Portability6566- Use `#!/usr/bin/env bash` shebang for portability across systems67- Check Bash version at script start: `(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))` for Bash 4.4+ features68- Validate required external commands exist: `command -v jq &>/dev/null || exit 1`69- Detect platform differences: `case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac`70- Handle GNU vs BSD tool differences (e.g., `sed -i` vs `sed -i ''`)71- Test scripts on all target platforms (Linux, macOS, BSD variants)72- Document minimum version requirements in script header comments73- Provide fallback implementations for platform-specific features74- Use built-in Bash features over external commands when possible for portability75- Avoid bashisms when POSIX compliance is required, document when using Bash-specific features7677## Readability & Maintainability7879- Use long-form options in scripts for clarity: `--verbose` instead of `-v`80- Employ consistent naming: snake_case for functions/variables, UPPER_CASE for constants81- Add section headers with comment blocks to organize related functions82- Keep functions under 50 lines; refactor larger functions into smaller components83- Group related functions together with descriptive section headers84- Use descriptive function names that explain purpose: `validate_input_file` not `check_file`85- Add inline comments for non-obvious logic, avoid stating the obvious86- Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)87- Place opening braces on same line for consistency: `function_name() {`88- Use blank lines to separate logical blocks within functions89- Document function parameters and return values in header comments90- Extract magic numbers and strings to named constants at top of script9192## Safety & Security Patterns9394- Declare constants with `readonly` to prevent accidental modification95- Use `local` keyword for all function variables to avoid polluting global scope96- Implement `timeout` for external commands: `timeout 30s curl ...` prevents hangs97- Validate file permissions before operations: `[[ -r "$file" ]] || exit 1`98- Use process substitution `<(command)` instead of temporary files when possible99- Sanitize user input before using in commands or file operations100- Validate numeric input with pattern matching: `[[ $num =~ ^[0-9]+$ ]]`101- Never use `eval` on user input; use arrays for dynamic command construction102- Set restrictive umask for sensitive operations: `(umask 077; touch "$secure_file")`103- Log security-relevant operations (authentication, privilege changes, file access)104- Use `--` to separate options from arguments: `rm -rf -- "$user_input"`105- Validate environment variables before using: `: "${REQUIRED_VAR:?not set}"`106- Check exit codes of all security-critical operations explicitly107- Use `trap` to ensure cleanup happens even on abnormal exit108109## Performance Optimization110111- Avoid subshells in loops; use `while read` instead of `for i in $(cat file)`112- Use Bash built-ins over external commands: `[[ ]]` instead of `test`, `${var//pattern/replacement}` instead of `sed`113- Batch operations instead of repeated single operations (e.g., one `sed` with multiple expressions)114- Use `mapfile`/`readarray` for efficient array population from command output115- Avoid repeated command substitutions; store result in variable once116- Use arithmetic expansion `$(( ))` instead of `expr` for calculations117- Prefer `printf` over `echo` for formatted output (faster and more reliable)118- Use associative arrays for lookups instead of repeated grepping119- Process files line-by-line for large files instead of loading entire file into memory120- Use `xargs -P` for parallel processing when operations are independent121122## Documentation Standards123124- Implement `--help` and `-h` flags showing usage, options, and examples125- Provide `--version` flag displaying script version and copyright information126- Include usage examples in help output for common use cases127- Document all command-line options with descriptions of their purpose128- List required vs optional arguments clearly in usage message129- Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures130- Include prerequisites section listing required commands and versions131- Add header comment block with script purpose, author, and modification date132- Document environment variables the script uses or requires133- Provide troubleshooting section in help for common issues134- Generate documentation with `shdoc` from special comment formats135- Create man pages using `shellman` for system integration136- Include architecture diagrams using Mermaid or GraphViz for complex scripts137138## Modern Bash Features (5.x)139140- **Bash 5.0**: Associative array improvements, `${var@U}` uppercase conversion, `${var@L}` lowercase141- **Bash 5.1**: Enhanced `${parameter@operator}` transformations, `compat` shopt options for compatibility142- **Bash 5.2**: `varredir_close` option, improved `exec` error handling, `EPOCHREALTIME` microsecond precision143- Check version before using modern features: `[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]`144- Use `${parameter@Q}` for shell-quoted output (Bash 4.4+)145- Use `${parameter@E}` for escape sequence expansion (Bash 4.4+)146- Use `${parameter@P}` for prompt expansion (Bash 4.4+)147- Use `${parameter@A}` for assignment format (Bash 4.4+)148- Employ `wait -n` to wait for any background job (Bash 4.3+)149- Use `mapfile -d delim` for custom delimiters (Bash 4.4+)150151## CI/CD Integration152153- **GitHub Actions**: Use `shellcheck-problem-matchers` for inline annotations154- **Pre-commit hooks**: Configure `.pre-commit-config.yaml` with `shellcheck`, `shfmt`, `checkbashisms`155- **Matrix testing**: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS156- **Container testing**: Use official bash:5.2 Docker images for reproducible tests157- **CodeQL**: Enable shell script scanning for security vulnerabilities158- **Actionlint**: Validate GitHub Actions workflow files that use shell scripts159- **Automated releases**: Tag versions and generate changelogs automatically160- **Coverage reporting**: Track test coverage and fail on regressions161- Example workflow: `shellcheck *.sh && shfmt -d *.sh && bats test/`162163## Security Scanning & Hardening164165- **SAST**: Integrate Semgrep with custom rules for shell-specific vulnerabilities166- **Secrets detection**: Use `gitleaks` or `trufflehog` to prevent credential leaks167- **Supply chain**: Verify checksums of sourced external scripts168- **Sandboxing**: Run untrusted scripts in containers with restricted privileges169- **SBOM**: Document dependencies and external tools for compliance170- **Security linting**: Use ShellCheck with security-focused rules enabled171- **Privilege analysis**: Audit scripts for unnecessary root/sudo requirements172- **Input sanitization**: Validate all external inputs against allowlists173- **Audit logging**: Log all security-relevant operations to syslog174- **Container security**: Scan script execution environments for vulnerabilities175176## Observability & Logging177178- **Structured logging**: Output JSON for log aggregation systems179- **Log levels**: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity180- **Syslog integration**: Use `logger` command for system log integration181- **Distributed tracing**: Add trace IDs for multi-script workflow correlation182- **Metrics export**: Output Prometheus-format metrics for monitoring183- **Error context**: Include stack traces, environment info in error logs184- **Log rotation**: Configure log file rotation for long-running scripts185- **Performance metrics**: Track execution time, resource usage, external call latency186- Example: `log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }`187188## Quality Checklist189190- Scripts pass ShellCheck static analysis with minimal suppressions191- Code is formatted consistently with shfmt using standard options192- Comprehensive test coverage with Bats including edge cases193- All variable expansions are properly quoted194- Error handling covers all failure modes with meaningful messages195- Temporary resources are cleaned up properly with EXIT traps196- Scripts support `--help` and provide clear usage information197- Input validation prevents injection attacks and handles edge cases198- Scripts are portable across target platforms (Linux, macOS)199- Performance is adequate for expected workloads and data sizes200201## Output202203- Production-ready Bash scripts with defensive programming practices204- Comprehensive test suites using bats-core or shellspec with TAP output205- CI/CD pipeline configurations (GitHub Actions, GitLab CI) for automated testing206- Documentation generated with shdoc and man pages with shellman207- Structured project layout with reusable library functions and dependency management208- Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)209- Performance benchmarks and profiling reports for critical workflows210- Security review with SAST, secrets scanning, and vulnerability reports211- Debugging utilities with trace modes, structured logging, and observability212- Migration guides for Bash 3→5 upgrades and legacy modernization213- Package distribution configurations (Homebrew formulas, deb/rpm specs)214- Container images for reproducible execution environments215216## Essential Tools217218### Static Analysis & Formatting219- **ShellCheck**: Static analyzer with `enable=all` and `external-sources=true` configuration220- **shfmt**: Shell script formatter with standard config (`-i 2 -ci -bn -sr -kp`)221- **checkbashisms**: Detect bash-specific constructs for portability analysis222- **Semgrep**: SAST with custom rules for shell-specific security issues223- **CodeQL**: GitHub's security scanning for shell scripts224225### Testing Frameworks226- **bats-core**: Maintained fork of Bats with modern features and active development227- **shellspec**: BDD-style testing framework with rich assertions and mocking228- **shunit2**: xUnit-style testing framework for shell scripts229- **bashing**: Testing framework with mocking support and test isolation230231### Modern Development Tools232- **bashly**: CLI framework generator for building command-line applications233- **basher**: Bash package manager for dependency management234- **bpkg**: Alternative bash package manager with npm-like interface235- **shdoc**: Generate markdown documentation from shell script comments236- **shellman**: Generate man pages from shell scripts237238### CI/CD & Automation239- **pre-commit**: Multi-language pre-commit hook framework240- **actionlint**: GitHub Actions workflow linter241- **gitleaks**: Secrets scanning to prevent credential leaks242- **Makefile**: Automation for lint, format, test, and release workflows243244## Common Pitfalls to Avoid245246- `for f in $(ls ...)` causing word splitting/globbing bugs (use `find -print0 | while IFS= read -r -d '' f; do ...; done`)247- Unquoted variable expansions leading to unexpected behavior248- Relying on `set -e` without proper error trapping in complex flows249- Using `echo` for data output (prefer `printf` for reliability)250- Missing cleanup traps for temporary files and directories251- Unsafe array population (use `readarray`/`mapfile` instead of command substitution)252- Ignoring binary-safe file handling (always consider NUL separators for filenames)253254## Dependency Management255256- **Package managers**: Use `basher` or `bpkg` for installing shell script dependencies257- **Vendoring**: Copy dependencies into project for reproducible builds258- **Lock files**: Document exact versions of dependencies used259- **Checksum verification**: Verify integrity of sourced external scripts260- **Version pinning**: Lock dependencies to specific versions to prevent breaking changes261- **Dependency isolation**: Use separate directories for different dependency sets262- **Update automation**: Automate dependency updates with Dependabot or Renovate263- **Security scanning**: Scan dependencies for known vulnerabilities264- Example: `basher install username/repo@version` or `bpkg install username/repo -g`265266## Advanced Techniques267268- **Error Context**: Use `trap 'echo "Error at line $LINENO: exit $?" >&2' ERR` for debugging269- **Safe Temp Handling**: `trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)`270- **Version Checking**: `(( BASH_VERSINFO[0] >= 5 ))` before using modern features271- **Binary-Safe Arrays**: `readarray -d '' files < <(find . -print0)`272- **Function Returns**: Use `declare -g result` for returning complex data from functions273- **Associative Arrays**: `declare -A config=([host]="localhost" [port]="8080")` for complex data structures274- **Parameter Expansion**: `${filename%.sh}` remove extension, `${path##*/}` basename, `${text//old/new}` replace all275- **Signal Handling**: `trap cleanup_function SIGHUP SIGINT SIGTERM` for graceful shutdown276- **Command Grouping**: `{ cmd1; cmd2; } > output.log` share redirection, `( cd dir && cmd )` use subshell for isolation277- **Co-processes**: `coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result` for bidirectional pipes278- **Here-documents**: `cat <<-'EOF'` with `-` strips leading tabs, quotes prevent expansion279- **Process Management**: `wait $pid` to wait for background job, `jobs -p` list background PIDs280- **Conditional Execution**: `cmd1 && cmd2` run cmd2 only if cmd1 succeeds, `cmd1 || cmd2` run cmd2 if cmd1 fails281- **Brace Expansion**: `touch file{1..10}.txt` creates multiple files efficiently282- **Nameref Variables**: `declare -n ref=varname` creates reference to another variable (Bash 4.3+)283- **Improved Error Trapping**: `set -Eeuo pipefail; shopt -s inherit_errexit` for comprehensive error handling284- **Parallel Execution**: `xargs -P $(nproc) -n 1 command` for parallel processing with CPU core count285- **Structured Output**: `jq -n --arg key "$value" '{key: $key}'` for JSON generation286- **Performance Profiling**: Use `time -v` for detailed resource usage or `TIMEFORMAT` for custom timing287288## References & Further Reading289290### Style Guides & Best Practices291- [Google Shell Style Guide](https://google.github.io/styleguide/shellguide.html) - Comprehensive style guide covering quoting, arrays, and when to use shell292- [Bash Pitfalls](https://mywiki.wooledge.org/BashPitfalls) - Catalog of common Bash mistakes and how to avoid them293- [Bash Hackers Wiki](https://wiki.bash-hackers.org/) - Comprehensive Bash documentation and advanced techniques294- [Defensive BASH Programming](https://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) - Modern defensive programming patterns295296### Tools & Frameworks297- [ShellCheck](https://github.com/koalaman/shellcheck) - Static analysis tool and extensive wiki documentation298- [shfmt](https://github.com/mvdan/sh) - Shell script formatter with detailed flag documentation299- [bats-core](https://github.com/bats-core/bats-core) - Maintained Bash testing framework300- [shellspec](https://github.com/shellspec/shellspec) - BDD-style testing framework for shell scripts301- [bashly](https://bashly.dannyb.co/) - Modern Bash CLI framework generator302- [shdoc](https://github.com/reconquest/shdoc) - Documentation generator for shell scripts303304### Security & Advanced Topics305- [Bash Security Best Practices](https://github.com/carlospolop/PEASS-ng) - Security-focused shell script patterns306- [Awesome Bash](https://github.com/awesome-lists/awesome-bash) - Curated list of Bash resources and tools307- [Pure Bash Bible](https://github.com/dylanaraps/pure-bash-bible) - Collection of pure bash alternatives to external commands