[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MZ107M1NHRBYRXCYN9517T":3,"skill-same:01M6MZ107M1NHRBYRXCYN9517T":77},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M6MZ107M1NHRBYRXCYN9517T","bash-defensive-patterns",null,"Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI\u002FCD pipelines, or system utilities requiring fault tolerance and safety.","snewhouse\u002Faa-ma-forge","snewhouse","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6317143?v=4","01M6MYYWF28C4KBQHHWB9SC6TS","Stephen J Newhouse","01M6MYYWJWQMDN2ZPFMJ584SSM",6,"MIT","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fbash-defensive-patterns\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fbash-defensive-patterns\u002FSKILL.md",[],[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"Bash","defensive","bash defensive patterns","patterns","for","writing","techniques","tolerance","Utilities","CI\u002FCD","scripts","fault tolerance","master","use","programming","system","shell scripts","shell","Safety","ci","2026-11-10 10:12:30",false,"---\n# Derived from https:\u002F\u002Fgithub.com\u002Fwshobson\u002Fagents\u002Fplugins\u002Fshell-scripting\u002Fskills\u002Fbash-defensive-patterns @ 5d65aa1 on 2026-10-09 — aa-ma-forge v0.17.0\nname: bash-defensive-patterns\ndescription: Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI\u002FCD pipelines, or system utilities requiring fault tolerance and safety.\n---\n\n# Bash Defensive Patterns\n\nComprehensive guidance for writing production-ready Bash scripts using defensive programming techniques, error handling, and safety best practices to prevent common pitfalls and ensure reliability.\n\n## When to Use This Skill\n\n- Writing production automation scripts\n- Building CI\u002FCD pipeline scripts\n- Creating system administration utilities\n- Developing error-resilient deployment automation\n- Writing scripts that must handle edge cases safely\n- Building maintainable shell script libraries\n- Implementing comprehensive logging and monitoring\n- Creating scripts that must work across different platforms\n\n## Core Defensive Principles\n\n### 1. Strict Mode\nEnable bash strict mode at the start of every script to catch errors early.\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail  # Exit on error, unset variables, pipe failures\n```\n\n**Key flags:**\n- `set -E`: Inherit ERR trap in functions\n- `set -e`: Exit when a command fails, with the exceptions below\n- `set -u`: Exit on undefined variable reference\n- `set -o pipefail`: Pipe fails if any command fails (not just last)\n\n**`set -e` caveats** ([BashFAQ\u002F105](https:\u002F\u002Fmywiki.wooledge.org\u002FBashFAQ\u002F105)). It is a safety net, not error handling. It does not fire:\n- inside `if`\u002F`while` conditions or on the left of `&&`\u002F`||`, including in any function called from there (SC2310);\n- in `$(…)` unless `shopt -s inherit_errexit` (bash ≥ 4.4);\n- for `local x=$(cmd)`, because `local` returns 0 (SC2155): declare, then assign.\n\n`pipefail` fails `producer | head` with SIGPIPE (141). Check status explicitly where a failure changes the result. `-E` only matters with an ERR trap; without one, `set -euo pipefail` is enough.\n\n### 2. Error Trapping and Cleanup\nImplement proper cleanup on script exit or error.\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Diagnostics go to stderr so they never corrupt stdout data\u002Fpipes\ntrap 'echo \"ERROR: line $LINENO: \\\"$BASH_COMMAND\\\" exited $?\" >&2' ERR\n\n# why: never name this TMPDIR — that is the system temp dir mktemp reads, and an early\n# exit would make the trap delete the *inherited* one (e.g. \u002Ftmp). Declare it before\n# the trap so the trap is safe even if the script dies before mktemp runs.\nwork_dir=\"\"\ntrap 'if [[ -n \"${work_dir:-}\" ]]; then rm -rf -- \"$work_dir\"; fi' EXIT\n\nwork_dir=$(mktemp -d)\n# Script code here\n```\n\n### 3. Variable Safety\nAlways quote variables to prevent word splitting and globbing issues.\n\n```bash\n# Wrong - unsafe\ncp $source $dest\n\n# Correct - safe\ncp \"$source\" \"$dest\"\n\n# Required variables - fail with message if unset\n: \"${REQUIRED_VAR:?REQUIRED_VAR is not set}\"\n```\n\n### 4. Array Handling\nUse arrays safely for complex data handling.\n\n```bash\n# Safe array iteration\ndeclare -a items=(\"item 1\" \"item 2\" \"item 3\")\n\nfor item in \"${items[@]}\"; do\n    echo \"Processing: $item\"\ndone\n\n# Reading output into array safely\nmapfile -t lines \u003C \u003C(some_command)\nreadarray -t numbers \u003C \u003C(seq 1 10)\n```\n\n### 5. Conditional Safety\nUse `[[ ]]` for Bash-specific features, `[ ]` for POSIX.\n\n```bash\n# Bash - safer\nif [[ -f \"$file\" && -r \"$file\" ]]; then\n    content=$(\u003C\"$file\")\nfi\n\n# POSIX - portable\nif [ -f \"$file\" ] && [ -r \"$file\" ]; then\n    content=$(cat \"$file\")\nfi\n\n# Test for existence before operations\nif [[ -z \"${VAR:-}\" ]]; then\n    echo \"VAR is not set or is empty\"\nfi\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Safe Script Directory Detection\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Correctly determine script directory\nSCRIPT_DIR=\"$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nSCRIPT_NAME=\"$(basename -- \"${BASH_SOURCE[0]}\")\"\n\necho \"Script location: $SCRIPT_DIR\u002F$SCRIPT_NAME\"\n```\n\n### Pattern 2: Comprehensive Function Templat\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Prefix for functions: handle_*, process_*, check_*, validate_*\n# Include documentation and error handling\n\nvalidate_file() {\n    local -r file=\"$1\"\n    local -r message=\"${2:-File not found: $file}\"\n\n    if [[ ! -f \"$file\" ]]; then\n        echo \"ERROR: $message\" >&2\n        return 1\n    fi\n    return 0\n}\n\nprocess_files() {\n    local -r input_dir=\"$1\"\n    local -r output_dir=\"$2\"\n\n    # Validate inputs\n    [[ -d \"$input_dir\" ]] || { echo \"ERROR: input_dir not a directory\" >&2; return 1; }\n\n    # Create output directory if needed\n    mkdir -p \"$output_dir\" || { echo \"ERROR: Cannot create output_dir\" >&2; return 1; }\n\n    # Process files safely\n    while IFS= read -r -d '' file; do\n        echo \"Processing: $file\"\n        # Do work\n    done \u003C \u003C(find \"$input_dir\" -maxdepth 1 -type f -print0)\n\n    return 0\n}\n```\n\n### Pattern 3: Safe Temporary File Handling\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# why: not TMPDIR (system temp dir that mktemp reads); declared before the trap so an\n# early exit can't delete anything it didn't create.\nwork_dir=\"\"\ntrap 'if [[ -n \"${work_dir:-}\" ]]; then rm -rf -- \"$work_dir\"; fi' EXIT\n\n# Create temporary directory\nwork_dir=$(mktemp -d) || { echo \"ERROR: Failed to create temp directory\" >&2; exit 1; }\n\n# Create temporary files in directory\ntmp_file1=\"$work_dir\u002Ftemp1.txt\"\ntmp_file2=\"$work_dir\u002Ftemp2.txt\"\n\n# Use temporary files\ntouch \"$tmp_file1\" \"$tmp_file2\"\n\necho \"Temp files created in: $work_dir\" >&2\n```\n\n### Pattern 4: Robust Argument Parsing\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Default values\nLOG_LEVEL=\"${LOG_LEVEL:-INFO}\"\nDRY_RUN=false\nOUTPUT_FILE=\"\"\nTHREADS=4\n\nusage() {\n    cat \u003C\u003CEOF\nUsage: $0 [OPTIONS]\n\nOptions:\n    -v, --verbose       Debug output (same as LOG_LEVEL=DEBUG)\n    -d, --dry-run       Run without making changes\n    -o, --output FILE   Output file path\n    -j, --jobs NUM      Number of parallel jobs\n    -h, --help          Show this help message\nEOF\n    exit \"${1:-0}\"\n}\n\n# Parse arguments\nwhile [[ $# -gt 0 ]]; do\n    case \"$1\" in\n        -v|--verbose)\n            LOG_LEVEL=DEBUG\n            shift\n            ;;\n        -d|--dry-run)\n            DRY_RUN=true\n            shift\n            ;;\n        -o|--output)\n            OUTPUT_FILE=\"$2\"\n            shift 2\n            ;;\n        -j|--jobs)\n            THREADS=\"$2\"\n            shift 2\n            ;;\n        -h|--help)\n            usage 0\n            ;;\n        --)\n            shift\n            break\n            ;;\n        *)\n            echo \"ERROR: Unknown option: $1\" >&2\n            usage 1\n            ;;\n    esac\ndone\n\n# Validate required arguments\n[[ -n \"$OUTPUT_FILE\" ]] || { echo \"ERROR: -o\u002F--output is required\" >&2; usage 1; }\n```\n\n### Pattern 5: Structured Logging\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# One line per event on stderr: ISO-8601 time, level, script, message (the hooks.log format)\nlog() { printf '%s %s %s: %s\\n' \"$(date -Is)\" \"$1\" \"${0##*\u002F}\" \"${*:2}\" >&2; }\nlog_info()  { log INFO \"$@\"; }\nlog_warn()  { log WARN \"$@\"; }\nlog_error() { log ERROR \"$@\"; }\nlog_debug() { [[ \"${LOG_LEVEL:-INFO}\" == DEBUG ]] || return 0; log DEBUG \"$@\"; }   # opt-in\n\n# Usage → 2026-10-12T09:41:00+01:00 INFO deploy.sh: Starting script\nlog_info \"Starting script\"\nlog_debug \"Debug information\"\nlog_warn \"Warning message\"\nlog_error \"Error occurred\"\n```\n\n### Pattern 6: Process Orchestration with Signals\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Track background processes\nPIDS=()\n\ncleanup() {\n    log_info \"Shutting down...\"\n\n    # Terminate all background processes\n    for pid in \"${PIDS[@]}\"; do\n        if kill -0 \"$pid\" 2>\u002Fdev\u002Fnull; then\n            kill -TERM \"$pid\" 2>\u002Fdev\u002Fnull || true\n        fi\n    done\n\n    # Wait for graceful shutdown\n    for pid in \"${PIDS[@]}\"; do\n        wait \"$pid\" 2>\u002Fdev\u002Fnull || true\n    done\n}\n\ntrap cleanup SIGTERM SIGINT\n\n# Start background tasks\nbackground_task &\nPIDS+=($!)\n\nanother_task &\nPIDS+=($!)\n\n# Wait for all background processes\nwait\n```\n\n### Pattern 7: Safe File Operations\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Use -i flag to move safely without overwriting\nsafe_move() {\n    local -r source=\"$1\"\n    local -r dest=\"$2\"\n\n    if [[ ! -e \"$source\" ]]; then\n        echo \"ERROR: Source does not exist: $source\" >&2\n        return 1\n    fi\n\n    if [[ -e \"$dest\" ]]; then\n        echo \"ERROR: Destination already exists: $dest\" >&2\n        return 1\n    fi\n\n    mv \"$source\" \"$dest\"\n}\n\n# Safe directory cleanup\nsafe_rmdir() {\n    local -r dir=\"$1\"\n\n    if [[ ! -d \"$dir\" ]]; then\n        echo \"ERROR: Not a directory: $dir\" >&2\n        return 1\n    fi\n\n    # Use -I flag to prompt before rm (BSD\u002FGNU compatible)\n    rm -rI -- \"$dir\"\n}\n\n# Atomic file writes\natomic_write() {\n    local -r target=\"$1\"\n    local -r tmpfile\n    tmpfile=$(mktemp) || return 1\n\n    # Write to temp file first\n    cat > \"$tmpfile\"\n\n    # Atomic rename\n    mv \"$tmpfile\" \"$target\"\n}\n```\n\n### Pattern 8: Idempotent Script Design\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Check if resource already exists\nensure_directory() {\n    local -r dir=\"$1\"\n\n    if [[ -d \"$dir\" ]]; then\n        log_info \"Directory already exists: $dir\"\n        return 0\n    fi\n\n    mkdir -p \"$dir\" || {\n        log_error \"Failed to create directory: $dir\"\n        return 1\n    }\n\n    log_info \"Created directory: $dir\"\n}\n\n# Ensure configuration state\nensure_config() {\n    local -r config_file=\"$1\"\n    local -r default_value=\"$2\"\n\n    if [[ ! -f \"$config_file\" ]]; then\n        echo \"$default_value\" > \"$config_file\"\n        log_info \"Created config: $config_file\"\n    fi\n}\n\n# Rerunning script multiple times should be safe\nensure_directory \"\u002Fvar\u002Fcache\u002Fmyapp\"\nensure_config \"\u002Fetc\u002Fmyapp\u002Fconfig\" \"log_level=info\"\n```\n\n### Pattern 9: Safe Command Substitution\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Use $() instead of backticks\nname=$(\u003C\"$file\")  # Modern, safe variable assignment from file\noutput=$(command -v python3)  # Get command location safely\n\n# Handle command substitution with error checking\nresult=$(command -v node) || {\n    log_error \"node command not found\"\n    return 1\n}\n\n# For multiple lines\nmapfile -t lines \u003C \u003C(grep \"pattern\" \"$file\")\n\n# NUL-safe iteration\nwhile IFS= read -r -d '' file; do\n    echo \"Processing: $file\"\ndone \u003C \u003C(find \u002Fpath -type f -print0)\n```\n\n### Pattern 10: Dry-Run Support\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\nDRY_RUN=\"${DRY_RUN:-false}\"\n\nrun_cmd() {\n    if [[ \"$DRY_RUN\" == \"true\" ]]; then\n        echo \"[DRY RUN] Would execute: $*\"\n        return 0\n    fi\n\n    \"$@\"\n}\n\n# Usage\nrun_cmd cp \"$source\" \"$dest\"\nrun_cmd rm \"$file\"\nrun_cmd chown \"$owner\" \"$target\"\n```\n\n\n## Reference Files\n\nFor detailed patterns and code examples, see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n","# Bash Defensive Patterns\n\nComprehensive guidance for writing production-ready Bash scripts using defensive programming techniques, error handling, and safety best practices to prevent common pitfalls and ensure reliability.\n\n## When to Use This Skill\n\n- Writing production automation scripts\n- Building CI\u002FCD pipeline scripts\n- Creating system administration utilities\n- Developing error-resilient deployment automation\n- Writing scripts that must handle edge cases safely\n- Building maintainable shell script libraries\n- Implementing comprehensive logging and monitoring\n- Creating scripts that must work across different platforms\n\n## Core Defensive Principles\n\n### 1. Strict Mode\nEnable bash strict mode at the start of every script to catch errors early.\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail  # Exit on error, unset variables, pipe failures\n```\n\n**Key flags:**\n- `set -E`: Inherit ERR trap in functions\n- `set -e`: Exit when a command fails, with the exceptions below\n- `set -u`: Exit on undefined variable reference\n- `set -o pipefail`: Pipe fails if any command fails (not just last)\n\n**`set -e` caveats** ([BashFAQ\u002F105](https:\u002F\u002Fmywiki.wooledge.org\u002FBashFAQ\u002F105)). It is a safety net, not error handling. It does not fire:\n- inside `if`\u002F`while` conditions or on the left of `&&`\u002F`||`, including in any function called from there (SC2310);\n- in `$(…)` unless `shopt -s inherit_errexit` (bash ≥ 4.4);\n- for `local x=$(cmd)`, because `local` returns 0 (SC2155): declare, then assign.\n\n`pipefail` fails `producer | head` with SIGPIPE (141). Check status explicitly where a failure changes the result. `-E` only matters with an ERR trap; without one, `set -euo pipefail` is enough.\n\n### 2. Error Trapping and Cleanup\nImplement proper cleanup on script exit or error.\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Diagnostics go to stderr so they never corrupt stdout data\u002Fpipes\ntrap 'echo \"ERROR: line $LINENO: \\\"$BASH_COMMAND\\\" exited $?\" >&2' ERR\n\n# why: never name this TMPDIR — that is the system temp dir mktemp reads, and an early\n# exit would make the trap delete the *inherited* one (e.g. \u002Ftmp). Declare it before\n# the trap so the trap is safe even if the script dies before mktemp runs.\nwork_dir=\"\"\ntrap 'if [[ -n \"${work_dir:-}\" ]]; then rm -rf -- \"$work_dir\"; fi' EXIT\n\nwork_dir=$(mktemp -d)\n# Script code here\n```\n\n### 3. Variable Safety\nAlways quote variables to prevent word splitting and globbing issues.\n\n```bash\n# Wrong - unsafe\ncp $source $dest\n\n# Correct - safe\ncp \"$source\" \"$dest\"\n\n# Required variables - fail with message if unset\n: \"${REQUIRED_VAR:?REQUIRED_VAR is not set}\"\n```\n\n### 4. Array Handling\nUse arrays safely for complex data handling.\n\n```bash\n# Safe array iteration\ndeclare -a items=(\"item 1\" \"item 2\" \"item 3\")\n\nfor item in \"${items[@]}\"; do\n    echo \"Processing: $item\"\ndone\n\n# Reading output into array safely\nmapfile -t lines \u003C \u003C(some_command)\nreadarray -t numbers \u003C \u003C(seq 1 10)\n```\n\n### 5. Conditional Safety\nUse `[[ ]]` for Bash-specific features, `[ ]` for POSIX.\n\n```bash\n# Bash - safer\nif [[ -f \"$file\" && -r \"$file\" ]]; then\n    content=$(\u003C\"$file\")\nfi\n\n# POSIX - portable\nif [ -f \"$file\" ] && [ -r \"$file\" ]; then\n    content=$(cat \"$file\")\nfi\n\n# Test for existence before operations\nif [[ -z \"${VAR:-}\" ]]; then\n    echo \"VAR is not set or is empty\"\nfi\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Safe Script Directory Detection\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Correctly determine script directory\nSCRIPT_DIR=\"$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nSCRIPT_NAME=\"$(basename -- \"${BASH_SOURCE[0]}\")\"\n\necho \"Script location: $SCRIPT_DIR\u002F$SCRIPT_NAME\"\n```\n\n### Pattern 2: Comprehensive Function Templat\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Prefix for functions: handle_*, process_*, check_*, validate_*\n# Include documentation and error handling\n\nvalidate_file() {\n    local -r file=\"$1\"\n    local -r message=\"${2:-File not found: $file}\"\n\n    if [[ ! -f \"$file\" ]]; then\n        echo \"ERROR: $message\" >&2\n        return 1\n    fi\n    return 0\n}\n\nprocess_files() {\n    local -r input_dir=\"$1\"\n    local -r output_dir=\"$2\"\n\n    # Validate inputs\n    [[ -d \"$input_dir\" ]] || { echo \"ERROR: input_dir not a directory\" >&2; return 1; }\n\n    # Create output directory if needed\n    mkdir -p \"$output_dir\" || { echo \"ERROR: Cannot create output_dir\" >&2; return 1; }\n\n    # Process files safely\n    while IFS= read -r -d '' file; do\n        echo \"Processing: $file\"\n        # Do work\n    done \u003C \u003C(find \"$input_dir\" -maxdepth 1 -type f -print0)\n\n    return 0\n}\n```\n\n### Pattern 3: Safe Temporary File Handling\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# why: not TMPDIR (system temp dir that mktemp reads); declared before the trap so an\n# early exit can't delete anything it didn't create.\nwork_dir=\"\"\ntrap 'if [[ -n \"${work_dir:-}\" ]]; then rm -rf -- \"$work_dir\"; fi' EXIT\n\n# Create temporary directory\nwork_dir=$(mktemp -d) || { echo \"ERROR: Failed to create temp directory\" >&2; exit 1; }\n\n# Create temporary files in directory\ntmp_file1=\"$work_dir\u002Ftemp1.txt\"\ntmp_file2=\"$work_dir\u002Ftemp2.txt\"\n\n# Use temporary files\ntouch \"$tmp_file1\" \"$tmp_file2\"\n\necho \"Temp files created in: $work_dir\" >&2\n```\n\n### Pattern 4: Robust Argument Parsing\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Default values\nLOG_LEVEL=\"${LOG_LEVEL:-INFO}\"\nDRY_RUN=false\nOUTPUT_FILE=\"\"\nTHREADS=4\n\nusage() {\n    cat \u003C\u003CEOF\nUsage: $0 [OPTIONS]\n\nOptions:\n    -v, --verbose       Debug output (same as LOG_LEVEL=DEBUG)\n    -d, --dry-run       Run without making changes\n    -o, --output FILE   Output file path\n    -j, --jobs NUM      Number of parallel jobs\n    -h, --help          Show this help message\nEOF\n    exit \"${1:-0}\"\n}\n\n# Parse arguments\nwhile [[ $# -gt 0 ]]; do\n    case \"$1\" in\n        -v|--verbose)\n            LOG_LEVEL=DEBUG\n            shift\n            ;;\n        -d|--dry-run)\n            DRY_RUN=true\n            shift\n            ;;\n        -o|--output)\n            OUTPUT_FILE=\"$2\"\n            shift 2\n            ;;\n        -j|--jobs)\n            THREADS=\"$2\"\n            shift 2\n            ;;\n        -h|--help)\n            usage 0\n            ;;\n        --)\n            shift\n            break\n            ;;\n        *)\n            echo \"ERROR: Unknown option: $1\" >&2\n            usage 1\n            ;;\n    esac\ndone\n\n# Validate required arguments\n[[ -n \"$OUTPUT_FILE\" ]] || { echo \"ERROR: -o\u002F--output is required\" >&2; usage 1; }\n```\n\n### Pattern 5: Structured Logging\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# One line per event on stderr: ISO-8601 time, level, script, message (the hooks.log format)\nlog() { printf '%s %s %s: %s\\n' \"$(date -Is)\" \"$1\" \"${0##*\u002F}\" \"${*:2}\" >&2; }\nlog_info()  { log INFO \"$@\"; }\nlog_warn()  { log WARN \"$@\"; }\nlog_error() { log ERROR \"$@\"; }\nlog_debug() { [[ \"${LOG_LEVEL:-INFO}\" == DEBUG ]] || return 0; log DEBUG \"$@\"; }   # opt-in\n\n# Usage → 2026-10-12T09:41:00+01:00 INFO deploy.sh: Starting script\nlog_info \"Starting script\"\nlog_debug \"Debug information\"\nlog_warn \"Warning message\"\nlog_error \"Error occurred\"\n```\n\n### Pattern 6: Process Orchestration with Signals\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Track background processes\nPIDS=()\n\ncleanup() {\n    log_info \"Shutting down...\"\n\n    # Terminate all background processes\n    for pid in \"${PIDS[@]}\"; do\n        if kill -0 \"$pid\" 2>\u002Fdev\u002Fnull; then\n            kill -TERM \"$pid\" 2>\u002Fdev\u002Fnull || true\n        fi\n    done\n\n    # Wait for graceful shutdown\n    for pid in \"${PIDS[@]}\"; do\n        wait \"$pid\" 2>\u002Fdev\u002Fnull || true\n    done\n}\n\ntrap cleanup SIGTERM SIGINT\n\n# Start background tasks\nbackground_task &\nPIDS+=($!)\n\nanother_task &\nPIDS+=($!)\n\n# Wait for all background processes\nwait\n```\n\n### Pattern 7: Safe File Operations\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Use -i flag to move safely without overwriting\nsafe_move() {\n    local -r source=\"$1\"\n    local -r dest=\"$2\"\n\n    if [[ ! -e \"$source\" ]]; then\n        echo \"ERROR: Source does not exist: $source\" >&2\n        return 1\n    fi\n\n    if [[ -e \"$dest\" ]]; then\n        echo \"ERROR: Destination already exists: $dest\" >&2\n        return 1\n    fi\n\n    mv \"$source\" \"$dest\"\n}\n\n# Safe directory cleanup\nsafe_rmdir() {\n    local -r dir=\"$1\"\n\n    if [[ ! -d \"$dir\" ]]; then\n        echo \"ERROR: Not a directory: $dir\" >&2\n        return 1\n    fi\n\n    # Use -I flag to prompt before rm (BSD\u002FGNU compatible)\n    rm -rI -- \"$dir\"\n}\n\n# Atomic file writes\natomic_write() {\n    local -r target=\"$1\"\n    local -r tmpfile\n    tmpfile=$(mktemp) || return 1\n\n    # Write to temp file first\n    cat > \"$tmpfile\"\n\n    # Atomic rename\n    mv \"$tmpfile\" \"$target\"\n}\n```\n\n### Pattern 8: Idempotent Script Design\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Check if resource already exists\nensure_directory() {\n    local -r dir=\"$1\"\n\n    if [[ -d \"$dir\" ]]; then\n        log_info \"Directory already exists: $dir\"\n        return 0\n    fi\n\n    mkdir -p \"$dir\" || {\n        log_error \"Failed to create directory: $dir\"\n        return 1\n    }\n\n    log_info \"Created directory: $dir\"\n}\n\n# Ensure configuration state\nensure_config() {\n    local -r config_file=\"$1\"\n    local -r default_value=\"$2\"\n\n    if [[ ! -f \"$config_file\" ]]; then\n        echo \"$default_value\" > \"$config_file\"\n        log_info \"Created config: $config_file\"\n    fi\n}\n\n# Rerunning script multiple times should be safe\nensure_directory \"\u002Fvar\u002Fcache\u002Fmyapp\"\nensure_config \"\u002Fetc\u002Fmyapp\u002Fconfig\" \"log_level=info\"\n```\n\n### Pattern 9: Safe Command Substitution\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\n# Use $() instead of backticks\nname=$(\u003C\"$file\")  # Modern, safe variable assignment from file\noutput=$(command -v python3)  # Get command location safely\n\n# Handle command substitution with error checking\nresult=$(command -v node) || {\n    log_error \"node command not found\"\n    return 1\n}\n\n# For multiple lines\nmapfile -t lines \u003C \u003C(grep \"pattern\" \"$file\")\n\n# NUL-safe iteration\nwhile IFS= read -r -d '' file; do\n    echo \"Processing: $file\"\ndone \u003C \u003C(find \u002Fpath -type f -print0)\n```\n\n### Pattern 10: Dry-Run Support\n\n```bash\n#!\u002Fbin\u002Fbash\nset -Eeuo pipefail\n\nDRY_RUN=\"${DRY_RUN:-false}\"\n\nrun_cmd() {\n    if [[ \"$DRY_RUN\" == \"true\" ]]; then\n        echo \"[DRY RUN] Would execute: $*\"\n        return 0\n    fi\n\n    \"$@\"\n}\n\n# Usage\nrun_cmd cp \"$source\" \"$dest\"\nrun_cmd rm \"$file\"\nrun_cmd chown \"$owner\" \"$target\"\n```\n\n\n## Reference Files\n\nFor detailed patterns and code examples, see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n",{"name":5,"description":7},"main","cd9a2962c9a7e0797fe440f7b1ba4ceccc16ae0d","claude-code\u002Fskills\u002Fbash-defensive-patterns",1,"https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge","https:\u002F\u002Fgithub.com\u002Fsnewhouse","Data Scientist, Bioinformatician, Dad, Husband, MS warrior","2026-11-12 06:45:42",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add snewhouse\u002Faa-ma-forge --skill bash-defensive-patterns",{"tool":59,"command":60},"bunx","bunx skills add snewhouse\u002Faa-ma-forge --skill bash-defensive-patterns",{"tool":62,"command":63},"pnpm","pnpm dlx skills add snewhouse\u002Faa-ma-forge --skill bash-defensive-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fbash-defensive-patterns\u002FSKILL.md",true,[67,71],{"path":68,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":16},"LICENSE","许可证",1068,{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002Fadvanced-patterns.md","REFERENCE","参考文档",2694,"https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fbash-defensive-patterns\u002Freferences\u002Fadvanced-patterns.md",[78,98,112,133,158,183],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":40},"01M6MZ588SD5DDH59H18PRNWEV","deploy-helper","You can use this to help with deploy stuff, deploying, deployments, releases, shipping, pushing to prod, going live, rollouts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fevals\u002Fskill-draft\u002Fdraft\u002FSKILL.md",[],[86,87,88,89,90,91,92,93,94,33,95,96,97],"deploy","deploy helper","helper","you","live","with","can","rollouts","shipping","deployments","releases","help",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":102,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":40},"01M6MZ54NEKRYXGMJ1KJWYMKM7","writing-for-agents","Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md.","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fwriting-for-agents\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fwriting-for-agents\u002FSKILL.md",[],[25,106,24,107,33,108,109,110,111],"writing for agents","line","instructions","read","editing","documents",{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":40},"01M6MZ500T0FH1G8TBSQV7G5G2","verify-plan","Slash entry for plan verification: runs plan-verification on an existing AA-MA plan, writes [task]-verification.md, and with --iterate loops until the plan converges. Use when the user types \u002Fverify-plan or wants the verification report saved.","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fverify-plan\u002FSKILL.md",[],[119,120,121,122,123,33,124,91,125,126,127,128,129,130,131,24,132],"verify","plan","verify plan","loops","task","user","verification","report","types","plan verification","entry","iterate","Existing","saved",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":40},"01M6MZ4V9ST4K54NT1SRBGCE7P","verify-impl","Post-impl adversarial review symmetric to \u002Fverify-plan. Dispatches up to 5 parallel audit agents (code-reviewer, security-auditor, tdd-sequence-auditor, context7-evidence-auditor, future-proofing-auditor) based on the milestone's plan-declared Audit-Profile. CRITICAL findings surface via AskUserQuestion accept\u002Fdispute\u002Fdefer panel before §7.3 user authorization. Introduced in v0.8.0 per ADR-0005. Invoked by Phase 6.8 of \u002Fexecute-aa-ma-milestone.","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Fverify-impl\u002FSKILL.md",[],[140,141,119,142,143,144,145,146,147,148,149,150,151,152,153,120,154,155,156,157],"impl","verify impl","adversarial","post","panel","via","critical","review","context7","up","evidence","reviewer","parallel","adr","audit","code","tdd","milestone",{"skillNo":159,"name":160,"nameZh":6,"description":161,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":162,"categories":163,"keywords":164,"publishedAt":40},"01M6MZ4K7CC9PMJ1KEY3F53RS1","understand-codebase","Onboard to a new, inherited, or shared codebase. Read it, understand it, map it, and learn its conventions, versioning, tests, tech stack, rules (AGENTS.md \u002F CLAUDE.md \u002F .cursorrules \u002F etc.), build\u002Frun\u002FCI, integrations, security posture, and repo health — then produce an honest pros\u002Fcons verdict, a \"contribute safely\" playbook, and an \"add a feature\" playbook, written to ONBOARDING.md at the repo root plus a .claude\u002Fonboarding\u002F set of deep-dives — and optionally author an AGENTS.md if one is missing, or review and propose improvements to an existing one. Tiered (Quick \u002F Standard \u002F Deep). Reuses codemem (index + diagrams), gsd-map-codebase, system-mapping, code-intelligence, impact-analysis rather than re-implementing them; Deep tier runs a TeamCreate agent-team. Keywords: new codebase, shared codebase, inherited code, onboard, understand this repo, how do I contribute, how do I add a feature, ramp up, get oriented, ONBOARDING.md, AGENTS.md, codebase walkthrough, joining a project.","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Funderstand-codebase\u002FSKILL.md",[],[165,166,167,149,168,169,170,39,171,172,173,174,175,176,177,178,179,180,181,182],"understand codebase","codebase","understand","walkthrough","analysis","SET","learn","diagrams","repo health","implementing","re","quick","impact","get","project","deep","shared","map",{"skillNo":184,"name":185,"nameZh":6,"description":186,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":82,"licenseFileUrl":6,"sourceHtmlUrl":187,"categories":188,"keywords":189,"publishedAt":40},"01M6MZ4D1ZC8MTW064QXY6WC76","token-compression","Output token compression for AA-MA workflows. Reduces response tokens by 40-75% while preserving full technical accuracy. Three intensity levels mapped to execution modes: lite (HITL), full (general), ultra (AFK). Auto-activates during AA-MA execution based on task Mode field. Manual activation via \u002Fcompress lite|full|ultra.","https:\u002F\u002Fgithub.com\u002Fsnewhouse\u002Faa-ma-forge\u002Fblob\u002Fmain\u002Fclaude-code\u002Fskills\u002Ftoken-compression\u002FSKILL.md",[],[190,191,192,193,194,195,196,24,197,198,145,199,200,201,202,123,203,204,205,206],"compression","token compression","token","workflows","output","modes","accuracy","mode","manual","intensity","tokens","hitl","three","general","auto","technical","execution"]