1---2name: bash-pro3description: Use when implementing bash functionality with production-grade patterns and safeguards.4---56# Bash Pro78## Focus Areas910- Defensive programming with strict error handling11- POSIX compliance and cross-platform portability12- Safe argument parsing and input validation13- Robust file operations and temporary resource management14- Process orchestration and pipeline safety15- Production-grade logging and error reporting16- Comprehensive testing with Bats framework17- Static analysis with ShellCheck and formatting with shfmt18- Modern Bash 5.x features and best practices19- CI/CD integration and automation workflows2021## Approach2223- Always use strict mode with `set -Eeuo pipefail` and proper error trapping24- Quote all variable expansions to prevent word splitting and globbing issues25- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`26- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance27- Implement comprehensive argument parsing with `getopts` and usage functions28- Create temporary files and directories safely with `mktemp` and cleanup traps29- Prefer `printf` over `echo` for predictable output formatting30- Use command substitution `$()` instead of backticks for readability31- Implement structured logging with timestamps and configurable verbosity32- Design scripts to be idempotent and support dry-run modes33- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+34- Employ `IFS=$'\n\t'` to prevent unwanted word splitting on spaces35- Validate inputs with `: "${VAR:?message}"` for required environment variables36- End option parsing with `--` and use `rm -rf -- "$dir"` for safe operations37- Support `--trace` mode with `set -x` opt-in for detailed debugging38- Use `xargs -0` with NUL boundaries for safe subprocess orchestration39- Employ `readarray`/`mapfile` for safe array population from command output40- Implement robust script directory detection: `SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"`41- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`4243## Compatibility & Portability4445- Use `#!/usr/bin/env bash` shebang for portability across systems46- Check Bash version at script start: `(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))` for Bash 4.4+ features47- Validate required external commands exist: `command -v jq &>/dev/null || exit 1`48- Detect platform differences: `case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac`49- Handle GNU vs BSD tool differences (e.g., `sed -i` vs `sed -i ''`)50- Test scripts on all target platforms (Linux, macOS, BSD variants)51- Document minimum version requirements in script header comments52- Provide fallback implementations for platform-specific features53- Use built-in Bash features over external commands when possible for portability54- Avoid bashisms when POSIX compliance is required, document when using Bash-specific features5556## Readability & Maintainability5758- Use long-form options in scripts for clarity: `--verbose` instead of `-v`59- Employ consistent naming: snake_case for functions/variables, UPPER_CASE for constants60- Add section headers with comment blocks to organize related functions61- Keep functions under 50 lines; refactor larger functions into smaller components62- Group related functions together with descriptive section headers63- Use descriptive function names that explain purpose: `validate_input_file` not `check_file`64- Add inline comments for non-obvious logic, avoid stating the obvious65- Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)66- Place opening braces on same line for consistency: `function_name() {`67- Use blank lines to separate logical blocks within functions68- Document function parameters and return values in header comments69- Extract magic numbers and strings to named constants at top of script7071## Safety & Security Patterns7273- Declare constants with `readonly` to prevent accidental modification74- Use `local` keyword for all function variables to avoid polluting global scope75- Implement `timeout` for external commands: `timeout 30s curl ...` prevents hangs76- Validate file permissions before operations: `[[ -r "$file" ]] || exit 1`77- Use process substitution `<(command)` instead of temporary files when possible78- Sanitize user input before using in commands or file operations79- Validate numeric input with pattern matching: `[[ $num =~ ^[0-9]+$ ]]`80- Never use `eval` on user input; use arrays for dynamic command construction81- Set restrictive umask for sensitive operations: `(umask 077; touch "$secure_file")`82- Log security-relevant operations (authentication, privilege changes, file access)83- Use `--` to separate options from arguments: `rm -rf -- "$user_input"`84- Validate environment variables before using: `: "${REQUIRED_VAR:?not set}"`85- Check exit codes of all security-critical operations explicitly86- Use `trap` to ensure cleanup happens even on abnormal exit8788## Performance Optimization8990- Avoid subshells in loops; use `while read` instead of `for i in $(cat file)`91- Use Bash built-ins over external commands: `[[ ]]` instead of `test`, `${var//pattern/replacement}` instead of `sed`92- Batch operations instead of repeated single operations (e.g., one `sed` with multiple expressions)93- Use `mapfile`/`readarray` for efficient array population from command output94- Avoid repeated command substitutions; store result in variable once95- Use arithmetic expansion `$(( ))` instead of `expr` for calculations96- Prefer `printf` over `echo` for formatted output (faster and more reliable)97- Use associative arrays for lookups instead of repeated grepping98- Process files line-by-line for large files instead of loading entire file into memory99- Use `xargs -P` for parallel processing when operations are independent100101## Documentation Standards102103- Implement `--help` and `-h` flags showing usage, options, and examples104- Provide `--version` flag displaying script version and copyright information105- Include usage examples in help output for common use cases106- Document all command-line options with descriptions of their purpose107- List required vs optional arguments clearly in usage message108- Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures109- Include prerequisites section listing required commands and versions110- Add header comment block with script purpose, author, and modification date111- Document environment variables the script uses or requires112- Provide troubleshooting section in help for common issues113- Generate documentation with `shdoc` from special comment formats114- Create man pages using `shellman` for system integration115- Include architecture diagrams using Mermaid or GraphViz for complex scripts116117## Modern Bash Features (5.x)118119- **Bash 5.0**: Associative array improvements, `${var@U}` uppercase conversion, `${var@L}` lowercase120- **Bash 5.1**: Enhanced `${parameter@operator}` transformations, `compat` shopt options for compatibility121- **Bash 5.2**: `varredir_close` option, improved `exec` error handling, `EPOCHREALTIME` microsecond precision122- Check version before using modern features: `[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]`123- Use `${parameter@Q}` for shell-quoted output (Bash 4.4+)124- Use `${parameter@E}` for escape sequence expansion (Bash 4.4+)125- Use `${parameter@P}` for prompt expansion (Bash 4.4+)126- Use `${parameter@A}` for assignment format (Bash 4.4+)127- Employ `wait -n` to wait for any background job (Bash 4.3+)128- Use `mapfile -d delim` for custom delimiters (Bash 4.4+)129130## CI/CD Integration131132- **GitHub Actions**: Use `shellcheck-problem-matchers` for inline annotations133- **Pre-commit hooks**: Configure `.pre-commit-config.yaml` with `shellcheck`, `shfmt`, `checkbashisms`134- **Matrix testing**: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS135- **Container testing**: Use official bash:5.2 Docker images for reproducible tests136- **CodeQL**: Enable shell script scanning for security vulnerabilities137- **Actionlint**: Validate GitHub Actions workflow files that use shell scripts138- **Automated releases**: Tag versions and generate changelogs automatically139- **Coverage reporting**: Track test coverage and fail on regressions140- Example workflow: `shellcheck *.sh && shfmt -d *.sh && bats test/`141142## Security Scanning & Hardening143144- **SAST**: Integrate Semgrep with custom rules for shell-specific vulnerabilities145- **Secrets detection**: Use `gitleaks` or `trufflehog` to prevent credential leaks146- **Supply chain**: Verify checksums of sourced external scripts147- **Sandboxing**: Run untrusted scripts in containers with restricted privileges148- **SBOM**: Document dependencies and external tools for compliance149- **Security linting**: Use ShellCheck with security-focused rules enabled150- **Privilege analysis**: Audit scripts for unnecessary root/sudo requirements151- **Input sanitization**: Validate all external inputs against allowlists152- **Audit logging**: Log all security-relevant operations to syslog153- **Container security**: Scan script execution environments for vulnerabilities154155## Observability & Logging156157- **Structured logging**: Output JSON for log aggregation systems158- **Log levels**: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity159- **Syslog integration**: Use `logger` command for system log integration160- **Distributed tracing**: Add trace IDs for multi-script workflow correlation161- **Metrics export**: Output Prometheus-format metrics for monitoring162- **Error context**: Include stack traces, environment info in error logs163- **Log rotation**: Configure log file rotation for long-running scripts164- **Performance metrics**: Track execution time, resource usage, external call latency165- Example: `log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }`166167## Quality Checklist168169- Scripts pass ShellCheck static analysis with minimal suppressions170- Code is formatted consistently with shfmt using standard options171- Comprehensive test coverage with Bats including edge cases172- All variable expansions are properly quoted173- Error handling covers all failure modes with meaningful messages174- Temporary resources are cleaned up properly with EXIT traps175- Scripts support `--help` and provide clear usage information176- Input validation prevents injection attacks and handles edge cases177- Scripts are portable across target platforms (Linux, macOS)178- Performance is adequate for expected workloads and data sizes179180## Output181182- Production-ready Bash scripts with defensive programming practices183- Comprehensive test suites using bats-core or shellspec with TAP output184- CI/CD pipeline configurations (GitHub Actions, GitLab CI) for automated testing185- Documentation generated with shdoc and man pages with shellman186- Structured project layout with reusable library functions and dependency management187- Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)188- Performance benchmarks and profiling reports for critical workflows189- Security review with SAST, secrets scanning, and vulnerability reports190- Debugging utilities with trace modes, structured logging, and observability191- Migration guides for Bash 3→5 upgrades and legacy modernization192- Package distribution configurations (Homebrew formulas, deb/rpm specs)193- Container images for reproducible execution environments194195## Essential Tools196197### Static Analysis & Formatting198199- **ShellCheck**: Static analyzer with `enable=all` and `external-sources=true` configuration200- **shfmt**: Shell script formatter with standard config (`-i 2 -ci -bn -sr -kp`)201- **checkbashisms**: Detect bash-specific constructs for portability analysis202- **Semgrep**: SAST with custom rules for shell-specific security issues203- **CodeQL**: GitHub's security scanning for shell scripts204205### Testing Frameworks206207- **bats-core**: Maintained fork of Bats with modern features and active development208- **shellspec**: BDD-style testing framework with rich assertions and mocking209- **shunit2**: xUnit-style testing framework for shell scripts210- **bashing**: Testing framework with mocking support and test isolation211212### Modern Development Tools213214- **bashly**: CLI framework generator for building command-line applications215- **basher**: Bash package manager for dependency management216- **bpkg**: Alternative bash package manager with npm-like interface217- **shdoc**: Generate markdown documentation from shell script comments218- **shellman**: Generate man pages from shell scripts219220### CI/CD & Automation221222- **pre-commit**: Multi-language pre-commit hook framework223- **actionlint**: GitHub Actions workflow linter224- **gitleaks**: Secrets scanning to prevent credential leaks225- **Makefile**: Automation for lint, format, test, and release workflows226227## Common Pitfalls to Avoid228229- `for f in $(ls ...)` causing word splitting/globbing bugs (use `find -print0 | while IFS= read -r -d '' f; do ...; done`)230- Unquoted variable expansions leading to unexpected behavior231- Relying on `set -e` without proper error trapping in complex flows232- Using `echo` for data output (prefer `printf` for reliability)233- Missing cleanup traps for temporary files and directories234- Unsafe array population (use `readarray`/`mapfile` instead of command substitution)235- Ignoring binary-safe file handling (always consider NUL separators for filenames)236237## Dependency Management238239- **Package managers**: Use `basher` or `bpkg` for installing shell script dependencies240- **Vendoring**: Copy dependencies into project for reproducible builds241- **Lock files**: Document exact versions of dependencies used242- **Checksum verification**: Verify integrity of sourced external scripts243- **Version pinning**: Lock dependencies to specific versions to prevent breaking changes244- **Dependency isolation**: Use separate directories for different dependency sets245- **Update automation**: Automate dependency updates with Dependabot or Renovate246- **Security scanning**: Scan dependencies for known vulnerabilities247- Example: `basher install username/repo@version` or `bpkg install username/repo -g`248249## Advanced Techniques250251- **Error Context**: Use `trap 'echo "Error at line $LINENO: exit $?" >&2' ERR` for debugging252- **Safe Temp Handling**: `trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)`253- **Version Checking**: `(( BASH_VERSINFO[0] >= 5 ))` before using modern features254- **Binary-Safe Arrays**: `readarray -d '' files < <(find . -print0)`255- **Function Returns**: Use `declare -g result` for returning complex data from functions256- **Associative Arrays**: `declare -A config=([host]="localhost" [port]="8080")` for complex data structures257- **Parameter Expansion**: `${filename%.sh}` remove extension, `${path##*/}` basename, `${text//old/new}` replace all258- **Signal Handling**: `trap cleanup_function SIGHUP SIGINT SIGTERM` for graceful shutdown259- **Command Grouping**: `{ cmd1; cmd2; } > output.log` share redirection, `( cd dir && cmd )` use subshell for isolation260- **Co-processes**: `coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result` for bidirectional pipes261- **Here-documents**: `cat <<-'EOF'` with `-` strips leading tabs, quotes prevent expansion262- **Process Management**: `wait $pid` to wait for background job, `jobs -p` list background PIDs263- **Conditional Execution**: `cmd1 && cmd2` run cmd2 only if cmd1 succeeds, `cmd1 || cmd2` run cmd2 if cmd1 fails264- **Brace Expansion**: `touch file{1..10}.txt` creates multiple files efficiently265- **Nameref Variables**: `declare -n ref=varname` creates reference to another variable (Bash 4.3+)266- **Improved Error Trapping**: `set -Eeuo pipefail; shopt -s inherit_errexit` for comprehensive error handling267- **Parallel Execution**: `xargs -P $(nproc) -n 1 command` for parallel processing with CPU core count268- **Structured Output**: `jq -n --arg key "$value" '{key: $key}'` for JSON generation269- **Performance Profiling**: Use `time -v` for detailed resource usage or `TIMEFORMAT` for custom timing270271## References & Further Reading272273### Style Guides & Best Practices274275- [Google Shell Style Guide](https://google.github.io/styleguide/shellguide.html) - Comprehensive style guide covering quoting, arrays, and when to use shell276- [Bash Pitfalls](https://mywiki.wooledge.org/BashPitfalls) - Catalog of common Bash mistakes and how to avoid them277- [Bash Hackers Wiki](https://wiki.bash-hackers.org/) - Comprehensive Bash documentation and advanced techniques278- [Defensive BASH Programming](https://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) - Modern defensive programming patterns279280### Tools & Frameworks281282- [ShellCheck](https://github.com/koalaman/shellcheck) - Static analysis tool and extensive wiki documentation283- [shfmt](https://github.com/mvdan/sh) - Shell script formatter with detailed flag documentation284- [bats-core](https://github.com/bats-core/bats-core) - Maintained Bash testing framework285- [shellspec](https://github.com/shellspec/shellspec) - BDD-style testing framework for shell scripts286- [bashly](https://bashly.dannyb.co/) - Modern Bash CLI framework generator287- [shdoc](https://github.com/reconquest/shdoc) - Documentation generator for shell scripts288289### Security & Advanced Topics290291- [Bash Security Best Practices](https://github.com/carlospolop/PEASS-ng) - Security-focused shell script patterns292- [Awesome Bash](https://github.com/awesome-lists/awesome-bash) - Curated list of Bash resources and tools293- [Pure Bash Bible](https://github.com/dylanaraps/pure-bash-bible) - Collection of pure bash alternatives to external commands294