Bash Master

作者 josiahsiegel5a1b1123b9e5无许可证58 个星标收录于 2026年10月8日更新于 2026年10月8日仓库3个月前更新

Expert bash/shell scripting across environments where Bash is available (Linux, macOS, Git Bash on Windows, WSL, containers). This is a Bash-focused skill - it does not provide PowerShell parity; on Windows the target is the Bash interpreter (Git Bash / WSL), not native PowerShell. PROACTIVELY activate for: (1) ANY bash/shell script task, (2) System automation, (3) DevOps/CI/CD scripts, (4) Build/deployment automation, (5) Script review/debugging, (6) Converting commands to scripts. Provides: Google Shell Style Guide compliance, ShellCheck validation, Bash portability across Linux/macOS/WSL/Git Bash/containers, POSIX compliance, security hardening, error handling, performance optimization, testing with BATS, and production-ready patterns. Ensures professional-grade, secure, portable Bash scripts every time.

AI 生成的概览

指导编写、审查和调试可在 Linux、macOS、WSL、Git Bash 和容器中运行的可移植、安全的 Bash 脚本。

功能
该技能提供编写和审查 Bash shell 脚本的说明与参考资料。内容涵盖安全前置设置、引号处理、POSIX 与 Bash 的可移植性、ShellCheck 校验、平台检测、安全加固、性能、BATS 测试和调试。它产出的是指导与代码模式,而非可执行脚本。
适用场景
适用于任何 Bash 或 shell 脚本任务,包括系统自动化、DevOps 与 CI/CD 脚本、构建或部署自动化、脚本审查和调试。不适用于 PowerShell、批处理文件或与脚本无关的通用命令帮助。
运行要求
该技能不附带脚本,仅为说明和参考文档。按其指导操作需要 Bash 环境,并可选使用 shellcheck、checkbashisms 和 BATS 等工具。

Bash Scripting Mastery

Scope and platform contract

This skill targets Bash itself, wherever Bash runs - Linux, macOS, WSL, Git Bash / MSYS2 on Windows, and Bash-based container images. It does not cover native PowerShell: a PowerShell script is a different language and should use powershell-master. On Windows, bash-master assumes the user is running Bash inside Git Bash, WSL, or a similar Bash environment, and addresses the MSYS path-translation quirks that result.

Repository conventions

Project-level conventions (Windows backslashes in tool calls, documentation discipline, etc.) live in the agent body and the windows-path-master plugin. This skill focuses on Bash content; do not duplicate that boilerplate here.

Quick reference

bash
#!/usr/bin/env bashset -euo pipefail  # Exit on error, undefined vars, pipe failuresIFS=$'\n\t'        # Safe word splitting# Run shellcheck your_script.sh before deployment.# Test on every target platform before production.

Bash-portability quick check:

bash
# Linux/macOS:       Full bash features# Git Bash (Windows): Most features, some system calls missing (no systemd, /proc differs)# WSL:               Effectively Linux; /mnt/c for Windows filesystem# Containers:        Depends on base image - alpine ships /bin/sh, not bash# POSIX mode:        Use /bin/sh and avoid bashisms

When to use this skill

Always activate for:

  • Writing or modifying any bash/shell script
  • Reviewing or refactoring existing scripts
  • Debugging shell script failures
  • DevOps automation, CI/CD pipelines, system administration
  • Cross-environment Bash portability (Linux <-> macOS <-> WSL <-> Git Bash <-> container)

Do not use this skill for:

  • PowerShell scripts - use powershell-master
  • Batch (.cmd/.bat) scripting
  • Generic command help unrelated to scripting

Core principles

1. Safety first

Every script should open with the safety preamble:

bash
#!/usr/bin/env bashset -e            # Exit on any errorset -u            # Exit on undefined variableset -o pipefail   # Catch failures mid-pipelineset -E            # Inherit ERR trap into functionsIFS=$'\n\t'       # Avoid word splitting on spaces
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"readonly SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"

2. POSIX vs Bash

Need to run on any UNIX sh#!/bin/sh, no [[ ]], no arrays, no process substitution
Modern Linux/macOS with Bash#!/usr/bin/env bash, prefer [[ ]], arrays, regex
Alpine/minimal containersEither install bash explicitly or write POSIX-compliant sh

3. Quoting

bash
# Always quote expansionsprocess "$file_path"        # correctprocess $file_path          # word-splitting bug
# Arraysfiles=("file 1.txt" "file 2.txt")process "${files[@]}"       # each element kept separateprocess "${files[*]}"       # joined as one string - usually wrong

4. ShellCheck

Run shellcheck on every script. Only disable warnings with a justification comment: # shellcheck disable=SC2086 reason: intentional word splitting.

See references/best_practices.md for the full quoting/style table and references/patterns_antipatterns.md for the common pitfalls.

Platform-specific considerations

Git Bash / MSYS2 (Windows)

Git Bash auto-converts Unix-style arguments to Windows paths. This is the largest single source of cross-platform Bash bugs on Windows.

bash
# The conversion: /foo becomes C:/Program Files/Git/usr/foo# Disable per-command:MSYS_NO_PATHCONV=1 command /path/that/should/stay/unix
# Manual conversionunix_path=$(cygpath -u "C:\Windows\System32")win_path=$(cygpath -w "/c/Users/username")
# Detect Git Bashif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "mingw"* ]]; then    : # Git Bashficase "${MSYSTEM:-}" in    MINGW64|MINGW32|MSYS) : ;;  # MSYS2 / Git Bash environmentesac
# Flags that look like pathscommand //e //s   # double-slash to suppress conversioncommand -e -s     # or use dash-options

Full Git Bash + Windows path notes live in references/windows-git-bash-paths.md.

Linux

GNU coreutils, /proc, systemd integration. Detect via [[ "$OSTYPE" == "linux-gnu"* ]].

macOS

BSD utilities behave differently from GNU. Most common gotchas: sed -i '' (empty string required), date flags differ, readlink -f not available on stock macOS.

bash
if command -v gsed >/dev/null; then SED=gsed; else SED=sed; fi

WSL

Effectively Linux. The Windows filesystem is mounted at /mnt/c/. Detect via grep -qi microsoft /proc/version.

Containers

Alpine images ship only /bin/sh (BusyBox). Write POSIX-compliant scripts or apk add bash. Container init quirks: PID 1 must reap children and handle signals. Detect via [ -f /.dockerenv ] or [ -n "$KUBERNETES_SERVICE_HOST" ].

Portable platform-detection template

bash
detect_platform() {    case "$OSTYPE" in        linux-gnu*)    echo "linux" ;;        darwin*)       echo "macos" ;;        msys*|cygwin*) echo "windows" ;;        *)             echo "unknown" ;;    esac}

Full per-platform tables (BSD-vs-GNU coreutils flags, WSL networking, container init patterns) live in references/platform_specifics.md.

Best practices (summary)

The full patterns - function design, error handling, input validation, argument parsing, logging - live in references/in-depth-patterns.md. The headline rules:

  • One concern per function; locals declared first; validate input; return non-zero on error.
  • Constants UPPER_CASE; locals lower_case; mark immutable values readonly.
  • Always check exit codes (if ! cmd, ||, traps, or a central error_exit helper).
  • Validate every external input - empty, format, length, charset.
  • Use getopts or a case-based argument parser; print usage and exit 1 on bad input.
  • Use a leveled logger that writes to stderr.

Security, performance, testing, debugging, advanced patterns

These each have dedicated sections in references/in-depth-patterns.md:

TopicWhat it covers
SecurityCommand-injection prevention, path-traversal guards, privilege management, secure temp files
PerformanceAvoiding subshells, bash built-ins vs externals, process substitution, array ops
TestingBATS unit tests, integration test patterns, CI/CD wiring
Debuggingset -x, PS4, conditional debug helpers, tracing and profiling
Advanced patternsSafe config parsing, parallel processing, signal handling, retries with backoff

Read that reference any time you need the canonical code template for one of those topics.

Reference files

  • references/platform_specifics.md [blocked] - Detailed platform differences and workarounds
  • references/best_practices.md [blocked] - Comprehensive industry standards and guidelines
  • references/patterns_antipatterns.md [blocked] - Common patterns and pitfalls with solutions
  • references/windows-git-bash-paths.md [blocked] - Git Bash / MSYS path-translation reference
  • references/in-depth-patterns.md [blocked] - Function design, security, performance, testing, debugging, advanced patterns
  • references/resources.md [blocked] - Official docs, style guides, tooling, and learning links

Success criteria

A Bash script written with this skill should:

  1. Pass shellcheck with no warnings
  2. Begin with set -euo pipefail
  3. Quote every variable expansion
  4. Print usage on -h/--help
  5. Decompose into testable functions
  6. Handle empty input, missing files, and unexpected arguments
  7. Run on every target platform (Linux/macOS/WSL/Git Bash/container) where it claims support
  8. Match the Google Shell Style Guide
  9. Clean up on exit (trap EXIT)
  10. Be unit-tested with BATS where logic is non-trivial
bash
# Pre-deployment checklistshellcheck script.shbash -n script.shbats test/script.bats./script.sh --helpDEBUG=true ./script.sh

Troubleshooting

Script fails on a different platform

  • checkbashisms script.sh to surface non-portable constructs.
  • command -v tool to verify a required tool is installed.
  • Diff command flags between GNU and BSD (sed --version etc.).

ShellCheck warnings

  • Read the rule explanation (shellcheck -W SC2086).
  • Fix the underlying issue; only disable a rule with a justification comment.

Works interactively but fails in cron

  • Cron has a minimal PATH - set PATH explicitly.
  • Use absolute paths.
  • Redirect stdout/stderr: ./script.sh >> /tmp/cron.log 2>&1.

Performance issues

  • Profile with time.
  • Enable set -x to find slow steps.
  • Replace external invocations with Bash built-ins where possible.

来源与署名

来源:josiahsiegel/claude-plugin-marketplace位于plugins/bash-master/skills/bash-master提交5a1b112

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架