[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-8020d7a7-887f-4ac7-8c65-747e2a586e7e":3,"$f0SiEslRWoB6CW07GAW8Yv4mrm_-_V9rNTBXRSpk824k":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"8020d7a7-887f-4ac7-8c65-747e2a586e7e","bash-pro","生产自动化、CI\u002FCD 防御型 Bash 脚本大师","cat_coding_devops","mod_coding","sickn33,coding","---\nname: bash-pro\ndescription: 'Master of defensive Bash scripting for production automation, CI\u002FCD\n\n  pipelines, and system utilities. Expert in safe, portable, and testable shell\n\n  scripts.\n\n  '\nrisk: critical\nsource: community\ndate_added: '2026-02-27'\n---\n## Use this skill when\n\n- Writing or reviewing Bash scripts for automation, CI\u002FCD, or ops\n- Hardening shell scripts for safety and portability\n\n## Do not use this skill when\n\n- You need POSIX-only shell without Bash features\n- The task requires a higher-level language for complex logic\n- You need Windows-native scripting (PowerShell)\n\n## Instructions\n\n1. Define script inputs, outputs, and failure modes.\n2. Apply strict mode and safe argument parsing.\n3. Implement core logic with defensive patterns.\n4. Add tests and linting with Bats and ShellCheck.\n\n## Safety\n\n- Treat input as untrusted; avoid eval and unsafe globbing.\n- Prefer dry-run modes before destructive actions.\n\n## Focus Areas\n\n- Defensive programming with strict error handling\n- POSIX compliance and cross-platform portability\n- Safe argument parsing and input validation\n- Robust file operations and temporary resource management\n- Process orchestration and pipeline safety\n- Production-grade logging and error reporting\n- Comprehensive testing with Bats framework\n- Static analysis with ShellCheck and formatting with shfmt\n- Modern Bash 5.x features and best practices\n- CI\u002FCD integration and automation workflows\n\n## Approach\n\n- Always use strict mode with `set -Eeuo pipefail` and proper error trapping\n- Quote all variable expansions to prevent word splitting and globbing issues\n- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`\n- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance\n- Implement comprehensive argument parsing with `getopts` and usage functions\n- Create temporary files and directories safely with `mktemp` and cleanup traps\n- Prefer `printf` over `echo` for predictable output formatting\n- Use command substitution `$()` instead of backticks for readability\n- Implement structured logging with timestamps and configurable verbosity\n- Design scripts to be idempotent and support dry-run modes\n- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+\n- Employ `IFS=$'\\n\\t'` to prevent unwanted word splitting on spaces\n- Validate inputs with `: \"${VAR:?message}\"` for required environment variables\n- End option parsing with `--` and use `rm -rf -- \"$dir\"` for safe operations\n- Support `--trace` mode with `set -x` opt-in for detailed debugging\n- Use `xargs -0` with NUL boundaries for safe subprocess orchestration\n- Employ `readarray`\u002F`mapfile` for safe array population from command output\n- Implement robust script directory detection: `SCRIPT_DIR=\"$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" && pwd -P)\"`\n- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`\n\n## Compatibility & Portability\n\n- Use `#!\u002Fusr\u002Fbin\u002Fenv bash` shebang for portability across systems\n- Check Bash version at script start: `(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))` for Bash 4.4+ features\n- Validate required external commands exist: `command -v jq &>\u002Fdev\u002Fnull || exit 1`\n- Detect platform differences: `case \"$(uname -s)\" in Linux*) ... ;; Darwin*) ... ;; esac`\n- Handle GNU vs BSD tool differences (e.g., `sed -i` vs `sed -i ''`)\n- Test scripts on all target platforms (Linux, macOS, BSD variants)\n- Document minimum version requirements in script header comments\n- Provide fallback implementations for platform-specific features\n- Use built-in Bash features over external commands when possible for portability\n- Avoid bashisms when POSIX compliance is required, document when using Bash-specific features\n\n## Readability & Maintainability\n\n- Use long-form options in scripts for clarity: `--verbose` instead of `-v`\n- Employ consistent naming: snake_case for functions\u002Fvariables, UPPER_CASE for constants\n- Add section headers with comment blocks to organize related functions\n- Keep functions under 50 lines; refactor larger functions into smaller components\n- Group related functions together with descriptive section headers\n- Use descriptive function names that explain purpose: `validate_input_file` not `check_file`\n- Add inline comments for non-obvious logic, avoid stating the obvious\n- Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)\n- Place opening braces on same line for consistency: `function_name() {`\n- Use blank lines to separate logical blocks within functions\n- Document function parameters and return values in header comments\n- Extract magic numbers and strings to named constants at top of script\n\n## Safety & Security Patterns\n\n- Declare constants with `readonly` to prevent accidental modification\n- Use `local` keyword for all function variables to avoid polluting global scope\n- Implement `timeout` for external commands: `timeout 30s curl ...` prevents hangs\n- Validate file permissions before operations: `[[ -r \"$file\" ]] || exit 1`\n- Use process substitution `\u003C(command)` instead of temporary files when possible\n- Sanitize user input before using in commands or file operations\n- Validate numeric input with pattern matching: `[[ $num =~ ^[0-9]+$ ]]`\n- Never use `eval` on user input; use arrays for dynamic command construction\n- Set restrictive umask for sensitive operations: `(umask 077; touch \"$secure_file\")`\n- Log security-relevant operations (authentication, privilege changes, file access)\n- Use `--` to separate options from arguments: `rm -rf -- \"$user_input\"`\n- Validate environment variables before using: `: \"${REQUIRED_VAR:?not set}\"`\n- Check exit codes of all security-critical operations explicitly\n- Use `trap` to ensure cleanup happens even on abnormal exit\n\n## Performance Optimization\n\n- Avoid subshells in loops; use `while read` instead of `for i in $(cat file)`\n- Use Bash built-ins over external commands: `[[ ]]` instead of `test`, `${var\u002F\u002Fpattern\u002Freplacement}` instead of `sed`\n- Batch operations instead of repeated single operations (e.g., one `sed` with multiple expressions)\n- Use `mapfile`\u002F`readarray` for efficient array population from command output\n- Avoid repeated command substitutions; store result in variable once\n- Use arithmetic expansion `$(( ))` instead of `expr` for calculations\n- Prefer `printf` over `echo` for formatted output (faster and more reliable)\n- Use associative arrays for lookups instead of repeated grepping\n- Process files line-by-line for large files instead of loading entire file into memory\n- Use `xargs -P` for parallel processing when operations are independent\n\n## Documentation Standards\n\n- Implement `--help` and `-h` flags showing usage, options, and examples\n- Provide `--version` flag displaying script version and copyright information\n- Include usage examples in help output for common use cases\n- Document all command-line options with descriptions of their purpose\n- List required vs optional arguments clearly in usage message\n- Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures\n- Include prerequisites section listing required commands and versions\n- Add header comment block with script purpose, author, and modification date\n- Document environment variables the script uses or requires\n- Provide troubleshooting section in help for common issues\n- Generate documentation with `shdoc` from special comment formats\n- Create man pages using `shellman` for system integration\n- Include architecture diagrams using Mermaid or GraphViz for complex scripts\n\n## Modern Bash Features (5.x)\n\n- **Bash 5.0**: Associative array improvements, `${var@U}` uppercase conversion, `${var@L}` lowercase\n- **Bash 5.1**: Enhanced `${parameter@operator}` transformations, `compat` shopt options for compatibility\n- **Bash 5.2**: `varredir_close` option, improved `exec` error handling, `EPOCHREALTIME` microsecond precision\n- Check version before using modern features: `[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]`\n- Use `${parameter@Q}` for shell-quoted output (Bash 4.4+)\n- Use `${parameter@E}` for escape sequence expansion (Bash 4.4+)\n- Use `${parameter@P}` for prompt expansion (Bash 4.4+)\n- Use `${parameter@A}` for assignment format (Bash 4.4+)\n- Employ `wait -n` to wait for any background job (Bash 4.3+)\n- Use `mapfile -d delim` for custom delimiters (Bash 4.4+)\n\n## CI\u002FCD Integration\n\n- **GitHub Actions**: Use `shellcheck-problem-matchers` for inline annotations\n- **Pre-commit hooks**: Configure `.pre-commit-config.yaml` with `shellcheck`, `shfmt`, `checkbashisms`\n- **Matrix testing**: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS\n- **Container testing**: Use official bash:5.2 Docker images for reproducible tests\n- **CodeQL**: Enable shell script scanning for security vulnerabilities\n- **Actionlint**: Validate GitHub Actions workflow files that use shell scripts\n- **Automated releases**: Tag versions and generate changelogs automatically\n- **Coverage reporting**: Track test coverage and fail on regressions\n- Example workflow: `shellcheck *.sh && shfmt -d *.sh && bats test\u002F`\n\n## Security Scanning & Hardening\n\n- **SAST**: Integrate Semgrep with custom rules for shell-specific vulnerabilities\n- **Secrets detection**: Use `gitleaks` or `trufflehog` to prevent credential leaks\n- **Supply chain**: Verify checksums of sourced external scripts\n- **Sandboxing**: Run untrusted scripts in containers with restricted privileges\n- **SBOM**: Document dependencies and external tools for compliance\n- **Security linting**: Use ShellCheck with security-focused rules enabled\n- **Privilege analysis**: Audit scripts for unnecessary root\u002Fsudo requirements\n- **Input sanitization**: Validate all external inputs against allowlists\n- **Audit logging**: Log all security-relevant operations to syslog\n- **Container security**: Scan script execution environments for vulnerabilities\n\n## Observability & Logging\n\n- **Structured logging**: Output JSON for log aggregation systems\n- **Log levels**: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity\n- **Syslog integration**: Use `logger` command for system log integration\n- **Distributed tracing**: Add trace IDs for multi-script workflow correlation\n- **Metrics export**: Output Prometheus-format metrics for monitoring\n- **Error context**: Include stack traces, environment info in error logs\n- **Log rotation**: Configure log file rotation for long-running scripts\n- **Performance metrics**: Track execution time, resource usage, external call latency\n- Example: `log_info() { logger -t \"$SCRIPT_NAME\" -p user.info \"$*\"; echo \"[INFO] $*\" >&2; }`\n\n## Quality Checklist\n\n- Scripts pass ShellCheck static analysis with minimal suppressions\n- Code is formatted consistently with shfmt using standard options\n- Comprehensive test coverage with Bats including edge cases\n- All variable expansions are properly quoted\n- Error handling covers all failure modes with meaningful messages\n- Temporary resources are cleaned up properly with EXIT traps\n- Scripts support `--help` and provide clear usage information\n- Input validation prevents injection attacks and handles edge cases\n- Scripts are portable across target platforms (Linux, macOS)\n- Performance is adequate for expected workloads and data sizes\n\n## Output\n\n- Production-ready Bash scripts with defensive programming practices\n- Comprehensive test suites using bats-core or shellspec with TAP output\n- CI\u002FCD pipeline configurations (GitHub Actions, GitLab CI) for automated testing\n- Documentation generated with shdoc and man pages with shellman\n- Structured project layout with reusable library functions and dependency management\n- Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)\n- Performance benchmarks and profiling reports for critical workflows\n- Security review with SAST, secrets scanning, and vulnerability reports\n- Debugging utilities with trace modes, structured logging, and observability\n- Migration guides for Bash 3→5 upgrades and legacy modernization\n- Package distribution configurations (Homebrew formulas, deb\u002Frpm specs)\n- Container images for reproducible execution environments\n\n## Essential Tools\n\n### Static Analysis & Formatting\n- **ShellCheck**: Static analyzer with `enable=all` and `external-sources=true` configuration\n- **shfmt**: Shell script formatter with standard config (`-i 2 -ci -bn -sr -kp`)\n- **checkbashisms**: Detect bash-specific constructs for portability analysis\n- **Semgrep**: SAST with custom rules for shell-specific security issues\n- **CodeQL**: GitHub's security scanning for shell scripts\n\n### Testing Frameworks\n- **bats-core**: Maintained fork of Bats with modern features and active development\n- **shellspec**: BDD-style testing framework with rich assertions and mocking\n- **shunit2**: xUnit-style testing framework for shell scripts\n- **bashing**: Testing framework with mocking support and test isolation\n\n### Modern Development Tools\n- **bashly**: CLI framework generator for building command-line applications\n- **basher**: Bash package manager for dependency management\n- **bpkg**: Alternative bash package manager with npm-like interface\n- **shdoc**: Generate markdown documentation from shell script comments\n- **shellman**: Generate man pages from shell scripts\n\n### CI\u002FCD & Automation\n- **pre-commit**: Multi-language pre-commit hook framework\n- **actionlint**: GitHub Actions workflow linter\n- **gitleaks**: Secrets scanning to prevent credential leaks\n- **Makefile**: Automation for lint, format, test, and release workflows\n\n## Common Pitfalls to Avoid\n\n- `for f in $(ls ...)` causing word splitting\u002Fglobbing bugs (use `find -print0 | while IFS= read -r -d '' f; do ...; done`)\n- Unquoted variable expansions leading to unexpected behavior\n- Relying on `set -e` without proper error trapping in complex flows\n- Using `echo` for data output (prefer `printf` for reliability)\n- Missing cleanup traps for temporary files and directories\n- Unsafe array population (use `readarray`\u002F`mapfile` instead of command substitution)\n- Ignoring binary-safe file handling (always consider NUL separators for filenames)\n\n## Dependency Management\n\n- **Package managers**: Use `basher` or `bpkg` for installing shell script dependencies\n- **Vendoring**: Copy dependencies into project for reproducible builds\n- **Lock files**: Document exact versions of dependencies used\n- **Checksum verification**: Verify integrity of sourced external scripts\n- **Version pinning**: Lock dependencies to specific versions to prevent breaking changes\n- **Dependency isolation**: Use separate directories for different dependency sets\n- **Update automation**: Automate dependency updates with Dependabot or Renovate\n- **Security scanning**: Scan dependencies for known vulnerabilities\n- Example: `basher install username\u002Frepo@version` or `bpkg install username\u002Frepo -g`\n\n## Advanced Techniques\n\n- **Error Context**: Use `trap 'echo \"Error at line $LINENO: exit $?\" >&2' ERR` for debugging\n- **Safe Temp Handling**: `trap 'rm -rf \"$tmpdir\"' EXIT; tmpdir=$(mktemp -d)`\n- **Version Checking**: `(( BASH_VERSINFO[0] >= 5 ))` before using modern features\n- **Binary-Safe Arrays**: `readarray -d '' files \u003C \u003C(find . -print0)`\n- **Function Returns**: Use `declare -g result` for returning complex data from functions\n- **Associative Arrays**: `declare -A config=([host]=\"localhost\" [port]=\"8080\")` for complex data structures\n- **Parameter Expansion**: `${filename%.sh}` remove extension, `${path##*\u002F}` basename, `${text\u002F\u002Fold\u002Fnew}` replace all\n- **Signal Handling**: `trap cleanup_function SIGHUP SIGINT SIGTERM` for graceful shutdown\n- **Command Grouping**: `{ cmd1; cmd2; } > output.log` share redirection, `( cd dir && cmd )` use subshell for isolation\n- **Co-processes**: `coproc proc { cmd; }; echo \"data\" >&\"${proc[1]}\"; read -u \"${proc[0]}\" result` for bidirectional pipes\n- **Here-documents**: `cat \u003C\u003C-'EOF'` with `-` strips leading tabs, quotes prevent expansion\n- **Process Management**: `wait $pid` to wait for background job, `jobs -p` list background PIDs\n- **Conditional Execution**: `cmd1 && cmd2` run cmd2 only if cmd1 succeeds, `cmd1 || cmd2` run cmd2 if cmd1 fails\n- **Brace Expansion**: `touch file{1..10}.txt` creates multiple files efficiently\n- **Nameref Variables**: `declare -n ref=varname` creates reference to another variable (Bash 4.3+)\n- **Improved Error Trapping**: `set -Eeuo pipefail; shopt -s inherit_errexit` for comprehensive error handling\n- **Parallel Execution**: `xargs -P $(nproc) -n 1 command` for parallel processing with CPU core count\n- **Structured Output**: `jq -n --arg key \"$value\" '{key: $key}'` for JSON generation\n- **Performance Profiling**: Use `time -v` for detailed resource usage or `TIMEFORMAT` for custom timing\n\n## References & Further Reading\n\n### Style Guides & Best Practices\n- [Google Shell Style Guide](https:\u002F\u002Fgoogle.github.io\u002Fstyleguide\u002Fshellguide.html) - Comprehensive style guide covering quoting, arrays, and when to use shell\n- [Bash Pitfalls](https:\u002F\u002Fmywiki.wooledge.org\u002FBashPitfalls) - Catalog of common Bash mistakes and how to avoid them\n- [Bash Hackers Wiki](https:\u002F\u002Fwiki.bash-hackers.org\u002F) - Comprehensive Bash documentation and advanced techniques\n- [Defensive BASH Programming](https:\u002F\u002Fwww.kfirlavi.com\u002Fblog\u002F2012\u002F11\u002F14\u002Fdefensive-bash-programming\u002F) - Modern defensive programming patterns\n\n### Tools & Frameworks\n- [ShellCheck](https:\u002F\u002Fgithub.com\u002Fkoalaman\u002Fshellcheck) - Static analysis tool and extensive wiki documentation\n- [shfmt](https:\u002F\u002Fgithub.com\u002Fmvdan\u002Fsh) - Shell script formatter with detailed flag documentation\n- [bats-core](https:\u002F\u002Fgithub.com\u002Fbats-core\u002Fbats-core) - Maintained Bash testing framework\n- [shellspec](https:\u002F\u002Fgithub.com\u002Fshellspec\u002Fshellspec) - BDD-style testing framework for shell scripts\n- [bashly](https:\u002F\u002Fbashly.dannyb.co\u002F) - Modern Bash CLI framework generator\n- [shdoc](https:\u002F\u002Fgithub.com\u002Freconquest\u002Fshdoc) - Documentation generator for shell scripts\n\n### Security & Advanced Topics\n- [Bash Security Best Practices](https:\u002F\u002Fgithub.com\u002Fcarlospolop\u002FPEASS-ng) - Security-focused shell script patterns\n- [Awesome Bash](https:\u002F\u002Fgithub.com\u002Fawesome-lists\u002Fawesome-bash) - Curated list of Bash resources and tools\n- [Pure Bash Bible](https:\u002F\u002Fgithub.com\u002Fdylanaraps\u002Fpure-bash-bible) - Collection of pure bash alternatives to external commands\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,196,295,"2026-05-16 13:08:21",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"DevOps","devops","mdi-cog-outline","CI\u002FCD、容器化、部署运维",3,162,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"885b0bf2-fe63-495b-a879-4d700db6bd36","1.0.0","bash-pro.zip",7548,"uploads\u002Fskills\u002F8020d7a7-887f-4ac7-8c65-747e2a586e7e\u002Fbash-pro.zip","9ca0e5bcf493926480183b1aaf36aa08989c606b90f72cce3800bbe413750d60","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":18689}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]