shell-script-pro
Write, edit, lint, format, or review shell scripts (.sh files or extensionless scripts with a shell shebang). Use for any Bash or POSIX sh scripting task.
- License 许可
- MIT
- 最近更新
- 2026-11-11
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- shell-script-pro
- description
- Write, edit, lint, format, or review shell scripts (.sh files or extensionless scripts with a shell shebang). Use for any Bash or POSIX sh scripting task.
02 资源文件 29
- 参考文档agents/openai.yaml132 B
- 资产文件assets/bats.snippets779 B
- 资产文件assets/editorconfig1.4 KB
- 资产文件assets/shellcheckrc1001 B
- 参考文档README.md5.5 KB
- 参考文档references/bad-code-examples.md7.3 KB
- 参考文档references/bash-strict-mode.md6.7 KB
- 参考文档references/bashism.md12.9 KB
- 参考文档references/coreutils-gotchas.md19.2 KB
- 参考文档references/dash-and-posh.md1.9 KB
- 参考文档references/function-names.txt6.9 KB
- 参考文档references/function-naming.md2.5 KB
- 参考文档references/layered-config.md12.4 KB
- 参考文档references/patterns.md7.7 KB
- 参考文档references/portability.md6.1 KB
- 参考文档references/portable-shell.md9.8 KB
- 参考文档references/pure-bash-bible.md44.1 KB
- 参考文档references/pure-sh-bible.md23.9 KB
- 参考文档references/security.md4.4 KB
- 参考文档references/sh-tricks.md22.9 KB
- 参考文档references/style-cheatsheet.md12.8 KB
- 参考文档references/testing.md1.7 KB
- 参考文档references/tools.md6.9 KB
- 参考文档references/variable-names.txt7.2 KB
- 脚本scripts/checkbashisms31.6 KB
- 脚本scripts/format.sh967 B
- 脚本scripts/init-configs.sh1.4 KB
- 脚本scripts/init-script.sh11.5 KB
- 脚本scripts/lint.sh2.1 KB
03 SKILL.md 正文
Shell Script Pro
Purpose
Produce shell scripts that are correct, readable, consistently styled, portable, and safe.
Overview
- Google's shell script style guide conventions
- Bash-first
set -euo pipefailfor Bash executables; explicit status checks for POSIX sh- snake_case function names; optional library namespaces
- explicit error handling on every failure path
- timestamped logging
- zero shellcheck warnings
- shfmt formatting
Operating Rules
- No script is done until shellcheck is clean at all severities with optional checks enabled (
-S style -o all) or every remaining finding carries an inline, reasoned suppression. - Always run
shfmtlast; never commit hand formatting that contradicts it. - When editing, match the file's existing style; do a full restyle only on request.
- Never invent a shellcheck code or shfmt flag. Cite only codes shellcheck itself printed, and verify flags with
shellcheck --list-optional,shfmt --help, or the man page; use the wiki only when network is available. - Prefer builtins over subprocesses; no
eval; no aliases in scripts; no SUID/SGID bits. - Every script handles errors explicitly and logs with levels to stderr — no silent failures, no bare
echofor diagnostics. - Keep this file's core stable; variant-specific or lengthy guidance belongs in
references/. - Use plain
snake_casefunction names in standalone scripts, regardless of script size. Do not prefix functions with the script name. Bash libraries may uselibrary_name::function_nameto avoid collisions; POSIX libraries use an underscore prefix such aslibrary_name_function_name. Avoid colon-delimited names in interactive completion functions.
Deviations from the Google Shell Style Guide
This skill follows Google's guide except where listed here. Each deviation is deliberate.
| Google says | This skill does | Why |
|---|---|---|
Executables start with #!/bin/bash |
#!/usr/bin/env bash when macOS or an unknown target is in scope; #!/bin/bash for Linux-only |
/bin/bash is bash 3.2 on macOS, and bash is often elsewhere (Homebrew, NixOS). See references/portability.md |
| Bash only, no need for POSIX compatibility | A POSIX sh track (references/portable-shell.md) |
Some targets (containers, BusyBox, legacy systems) only have sh |
| Rewrite in another language past ~100 lines | Advisory: tell the user once, then write the best shell to the standard | Shell is sometimes the only option, so this is not a blocker |
| Shell is for small utilities | Ships larger helpers (init-script.sh scaffold, references/layered-config.md) |
They serve real tools that must stay in shell; keep them to what the script needs |
set options, err() helper |
Adds set -euo pipefail, an ERR trap, leveled info/warn/err/debug helpers, shellcheck -o all |
Stricter failure handling; Google's rules still hold |
| Prefer builtins over external commands | Scaffold's log uses printf '%(...)T' on bash 4.2+ and falls back to date below that |
macOS ships bash 3.2 |
echo in examples |
printf '%s\n' for variable data |
echo handles -n, -e and backslashes differently across shells |
Workflow
The scaffold and strict-mode instructions below apply to Bash targets. For POSIX sh, use Portable shell decisions. Override the configuration template's shell=bash setting with shellcheck -s sh or the applicable project setting.
-
Classify the target. Executable or library? Bash (default) or POSIX sh?
- Executables: no extension preferred (or
.shif a build rule renames it);#!/usr/bin/env bashwhen macOS is in scope,#!/bin/bashfor Linux-only scripts (seereferences/portability.md); executable bit set. - Libraries: must end in
.sh, must not be executable, must carry function header comments. - POSIX sh (
#!/bin/sh): read Portable shell decisions. Record the minimum POSIX edition, shell versions, and utility implementations. Useshellcheck -s shandshfmt -ln=posix; runscripts/checkbashisms, and test withdashplus the deployment shells (seereferences/dash-and-posh.md). The Bash scaffold,ERRtrap, arrays, andlocalconventions do not apply. Do not assume POSIX.1-2024 additions are available on older shells. - Extensionless scripts are detected by shfmt via shebang; EditorConfig
[[bash]]sections cover them (seereferences/tools.md).
- Executables: no extension preferred (or
-
Scaffold or open. New script: generate from
scripts/init-script.sh(ships thelogcore with color-on-tty +NO_COLOR+QUIET,info/warn/err/debug,die(theEXITtrap does the cleanup), theERR-trap/__on_errorpattern fromreferences/bash-strict-mode.md,require_vars,cleanuptrap,check_preconditions,run_cmdwith-ndry-run,getopts+usage()). Existing script: keep its established style for the edit; apply the full standard only to new files or when a restyle was requested. If the project lacks.shellcheckrc/.editorconfig, install the templates withscripts/init-configs.sh(copies the.editorconfigand.shellcheckrctemplates into the project root, never overwrites). -
Write to the standard. Headline rules:
- Functions and variables: lowercase
snake_case(functions verb-first). Constants and exported variables:UPPER_SNAKE, declared at the top; usereadonly/export, notdeclare -xr; make a runtime-set constantreadonlyimmediately. Mutable script state stays lowercase. Pick names fromreferences/function-names.txtandreferences/variable-names.txtbefore inventing new ones. - One job per function (Single Responsibility): if it needs "and" to describe or has no short verb-first name, split it.
mainonly coordinates. - Separate output from status: data on stdout (
printf '%s\n'), success/failure viareturn(0-255). Never return a string throughreturn. - Scope every function variable with
local; declare separately from a command-substitution assignment (local xthenx="$(cmd)"), neverlocal x="$(cmd)". - Expansion: quote everything; brace named variables (
"${var}"); do not brace single-character specials or positionals ("$1","$?","$@") except${10}+ or to avoid ambiguity. - Use
[[ ]],$( ),(( )); quote every expansion; use arrays for argument lists. - Parse options with
getoptsplususage(). - Handle every failure path explicitly: no silent failures, errors to stderr, leveled timestamped logs with debug behind a flag, temp artifacts cleaned up with
trap. - End the script with a bare
main "$@". Never wrap it in||/&&/if: that suppressesset -eand theERRtrap insidemain.
Read the matching reference when the situation applies:
- Always:
references/style-cheatsheet.md(Google guide, condensed, including portability, error handling, logging),references/function-naming.md,references/bash-strict-mode.md(full strict-mode header andERR-trap pattern). - Script takes configuration:
references/layered-config.md(eval-free; defaults < file < env < args). - Looking for a ready-made solution:
references/patterns.md. - Choosing a shebang or target:
references/portability.md. - Handling untrusted input:
references/security.md.
- Functions and variables: lowercase
-
Lint. Run
scripts/lint.sh(shellcheck-x -S style -o all+shfmt -d). Fix every finding. A suppression is allowed only as# shellcheck disable=SCxxxx # <reason>with a real reason; look codes up on the shellcheck wiki, never invent them.references/bad-code-examples.mdis the gallery of patterns shellcheck catches. -
Format. Run
scripts/format.sh(shfmt -i 2 -ci -bn -s -w), honoring any.editorconfig. Never hand-format around shfmt's output. -
Verify.
shfmtparsing doubles as a strict syntax check (stricter thanbash -n). Smoke-run with representative inputs, including failure cases (missing args, missing commands, bad paths); usebashdbfor interactive debugging when behavior is wrong. For scripts with real logic, addbatstests — seereferences/testing.md. -
Report per the Output Contract.
Review mode
When asked to review (not change) a script: run scripts/lint.sh on it, walk the Output Contract as a checklist against the untouched file, and report findings ordered by severity (correctness/safety first, then portability, then style), each with a file:line reference and the concrete fix. Do not edit the file. If the script is vendored third-party code, say so and apply the vendored-code rule from references/tools.md instead of the full standard.
Output Contract
- Path(s) of every script created or changed.
- shellcheck result: clean, or each remaining code listed with its justification.
- shfmt: flags applied; any region intentionally left unformatted and why.
- Function design: each function has one job; data on stdout, status via
return; every function variable islocal. - Naming audit: plain snake_case names in standalone scripts; optional library namespaces and private prefixes where appropriate.
- Portability: bashisms flagged for POSIX targets; no unchecked GNU-only assumptions.
- Error handling: every failure path handled explicitly;
cdguarded; destructive commands guarded (${var:?}); traps clean up temp files. - Logging: leveled (INFO/WARN/ERROR/DEBUG), timestamped, stderr; stdout reserved for the script's real output; no bare
echodiagnostics. - Testing: smoke-run cases covered;
batstests added/updated for logic-bearing scripts (seereferences/testing.md). - Short changelog: what changed and what it was tested with.
Tooling
shellcheck -x -S style -o all <file>— linter and static analysis;-xfollowssource; severities: error, warning, info, style. Look up codes at https://github.com/koalaman/shellcheck/wiki ; also https://www.shellcheck.net/..shellcheckrctemplate inassets/shellcheckrc:shell=bash,severity=style,external-sources=true,enable=all(strict optional checks),SC1091disabled with reason. Install withscripts/init-configs.sh.shfmt -i 2 -ci -bn -s -w <file>— format to the Google-like preset (2-space indent, indented case branches, binary operators start the line, simplify).-dshows diffs without writing (CI-friendly);-llists files needing formatting;-f .finds shell files recursively;-ln=bash|posixforces the dialect..editorconfig— shfmt reads it; use[*.sh]plus[[bash]]for extensionless scripts. Install the template withscripts/init-configs.sh(source:assets/editorconfig).scripts/checkbashisms— vendored copy (devscriptsmain, GPL-2.0+; see README "Third-party code") of the Debian devscripts bashism checker (Perl). Run it on#!/bin/shscripts to catch bash-only constructs; seereferences/tools.mdfor the distro packages.bashdb— interactive bash debugger (bashdb script.sh).bash-language-server— editor integration (diagnostics, completion).- Install commands (apt/apt-get/yum/dnf/rpm-ostree/brew/Go): see
references/tools.md.
References
- Google Shell Style Guide — https://google.github.io/styleguide/shellguide.html
- BashPitfalls — https://mywiki.wooledge.org/BashPitfalls ; BashFAQ — https://mywiki.wooledge.org/BashFAQ
- TLDP Advanced Bash-Scripting Guide — http://tldp.org/LDP/abs/html/
- pure-bash-bible — https://github.com/dylanaraps/pure-bash-bible
04 同仓库更多 Skills
shell-script-expert
Use when the user asks "review this script", "write a bash script", "fix my shell script", "make this script safer", "why does this script fail", "convert this to a script", or working with .sh/.bash files, sh/bash syntax, shellcheck, cronjobs, and bash one-liners.
prose-synthesize
Turn unstructured notes into a structured, actionable plan. Use when given brain dumps, stream-of-consciousness, or scattered thoughts needing order.
prose-distill
Condense verbose text to its essence. Use when asked to condense, tighten, shorten, reduce verbosity, or omit needless words while preserving substance.
mindcraft
暂无简介
learn
Tutor for intellectual understanding: teach how or why something works rather than complete a task or provide an evaluative verdict. Trigger for explicit learning requests (teach, explain, ELI5, walkthroughs, quizzes, flashcards, definitions); terse concept prompts; confusion signals; prerequisite or sequencing questions; and conceptual questions about mechanisms, causes, or dynamics. Do not trigger for task completion (coding, writing, calculation, or translation), factual or news lookup, personal troubleshooting, resource recommendations, or opinion and interpretive verdicts.
deployment-readiness
Use to check deployment readiness of a host.