К основному содержанию
скилл CX Codex

shell — скилл для Claude Code: правила безопасных bash-скриптов

Скилл с 49 правилами для bash и POSIX sh: цитирование переменных, строгий режим, обработка ошибок. Пригодится, когда агент пишет или правит скрипты.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pproenca/dot-skills --skill shell -a claude-code
Открыть на GitHub

Что делает shell

Скилл shell — это набор из 49 правил по девяти категориям, от критичных до стилевых. Внутри разобраны безопасность, переносимость, обработка ошибок, работа с переменными, цитирование, структура функций, условия, производительность и форматирование. К каждому правилу идут объяснение и примеры: как делать не надо и как правильно.

Агент подхватывает скилл, когда вы пишете новый скрипт, разбираете чужой на уязвимости или переносите код между Linux, macOS и контейнером. Триггеры — bash, sh, POSIX, ShellCheck, set -euo pipefail. Работает и на командах RUN в Dockerfile, рецептах Makefile, скриптах CI, заданиях cron и директивах ExecStart в systemd.

Правила разложены по отдельным файлам в references/, поэтому агент читает только нужный раздел, а не весь справочник. Ставится одной командой через npx skills; для GitHub Copilot есть отдельный установщик gh skill install. Если в вашем окружении прокси или приватное зеркало npm, настройте его в конфиге npm, а не флагами в строке установки.

Какие задачи решает

  • поймать инъекцию команды в скрипте, который принимает аргументы извне
  • убрать bash-измы из скрипта, который должен работать под POSIX sh
  • добавить строгий режим и не пропустить падение в середине пайплайна
  • починить скрипт, который молча падает и ничего не пишет в stderr
  • привести к порядку quoting и разбор аргументов в старом скрипте

Примеры запросов агенту

  • Перепиши этот скрипт по правилам скилла shell: убери небезопасное цитирование и добавь строгий режим
  • Проверь мой deploy.sh на инъекции команд и проблемы переносимости
  • Разбери RUN в Dockerfile — что тут не так с точки зрения shell-правил

Как установить shell

1Через Skills CLI (Vercel)

npx skills add pproenca/dot-skills --skill shell -a claude-code

2Вручную: положить файлы

~/.claude/skills/shell/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/shell/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о shell

Как установить shell в Claude?

Выполните npx skills add pproenca/dot-skills --skill shell -a claude-code. Файл скилла окажется в ~/.claude/skills/shell/SKILL.md.

Что делает скилл shell?

Даёт агенту справочник из 49 правил по bash и POSIX sh: безопасность, переносимость, обработка ошибок, переменные, цитирование, функции, условия, производительность и стиль. Агент обращается к нему при написании, проверке и рефакторинге скриптов.

На чём скилл срабатывает?

Триггеры — bash, sh, POSIX, ShellCheck, set -euo pipefail. Кроме обычных скриптов это команды RUN в Dockerfile, рецепты Makefile, скрипты CI, cron и ExecStart в systemd.

Исходный текст

SKILL.md · MIT
---
name: shell
description: Shell scripting best practices for writing safe, portable, and maintainable bash/sh scripts. Use when writing, reviewing, or refactoring shell scripts, Dockerfile RUN commands, Makefile recipes, CI pipeline scripts, cron jobs, or systemd ExecStart directives. Triggers on bash, sh, POSIX, ShellCheck, error handling, quoting, variables, set -euo pipefail.
---

# Shell Scripts Best Practices (Community)

Comprehensive best practices guide for shell scripting, designed for AI agents and LLMs. Contains 49 rules across 9 categories, prioritized by impact from critical (safety, portability) to incremental (style). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics.

## When to Apply

Reference these guidelines when:
- Writing new bash or POSIX shell scripts
- Reviewing shell scripts for security vulnerabilities
- Debugging scripts that fail silently or behave unexpectedly
- Porting scripts between Linux, macOS, and containers
- Optimizing shell script performance
- Setting up CI/CD pipelines with shell scripts

## Rule Categories by Priority

| Priority | Category | Impact | Prefix | Rules |
|----------|----------|--------|--------|-------|
| 1 | Safety & Security | CRITICAL | `safety-` | 6 |
| 2 | Portability | CRITICAL | `port-` | 5 |
| 3 | Error Handling | HIGH | `err-` | 8 |
| 4 | Variables & Data | HIGH | `var-` | 5 |
| 5 | Quoting & Expansion | MEDIUM-HIGH | `quote-` | 6 |
| 6 | Functions & Structure | MEDIUM | `func-` | 5 |
| 7 | Testing & Conditionals | MEDIUM | `test-` | 5 |
| 8 | Performance | LOW-MEDIUM | `perf-` | 6 |
| 9 | Style & Formatting | LOW | `style-` | 3 |

## Quick Reference

### 1. Safety & Security (CRITICAL)

- [`safety-command-injection`](references/safety-command-injection.md) - Prevent command injection from user input
- [`safety-eval-avoidance`](references/safety-eval-avoidance.md) - Avoid eval for dynamic commands
- [`safety-absolute-paths`](references/safety-absolute-paths.md) - Use absolute paths for external commands
- [`safety-temp-files`](references/safety-temp-files.md) - Create secure temporary files
- [`safety-suid-forbidden`](references/safety-suid-forbidden.md) - Never use SUID/SGID on shell scripts
- [`safety-argument-injection`](references/safety-argument-injection.md) - Prevent argument injection with double dash

### 2. Portability (CRITICAL)

- [`port-shebang-selection`](references/port-shebang-selection.md) - Choose shebang based on portability needs
- [`port-avoid-bashisms`](references/port-avoid-bashisms.md) - Avoid bashisms in POSIX scripts
- [`port-printf-over-echo`](references/port-printf-over-echo.md) - Use printf instead of echo for portability
- [`port-export-syntax`](references/port-export-syntax.md) - Use portable export syntax
- [`port-test-portability`](references/port-test-portability.md) - Use portable test constructs

### 3. Error Handling (HIGH)

- [`err-strict-mode`](references/err-strict-mode.md) - Use strict mode for error detection
- [`err-exit-codes`](references/err-exit-codes.md) - Use meaningful exit codes
- [`err-trap-cleanup`](references/err-trap-cleanup.md) - Use trap for cleanup on exit
- [`err-stderr-messages`](references/err-stderr-messages.md) - Send error messages to stderr
- [`err-pipefail`](references/err-pipefail.md) - Use pipefail to catch pipeline errors
- [`err-check-commands`](references/err-check-commands.md) - Check command success explicitly
- [`err-shellcheck`](references/err-shellcheck.md) - Use ShellCheck for static analysis
- [`err-debug-tracing`](references/err-debug-tracing.md) - Use debug tracing with set -x and PS4

### 4. Variables & Data (HIGH)

- [`var-use-arrays`](references/var-use-arrays.md) - Use arrays for lists instead of strings
- [`var-local-scope`](references/var-local-scope.md) - Use local for function variables
- [`var-naming-conventions`](references/var-naming-conventions.md) - Follow variable naming conventions
- [`var-readonly-constants`](references/var-readonly-constants.md) - Use readonly for constants
- [`var-default-values`](references/var-default-values.md) - Use parameter expansion for defaults

### 5. Quoting & Expansion (MEDIUM-HIGH)

- [`quote-always-quote-variables`](references/quote-always-quote-variables.md) - Always quote variable expansions
- [`quote-dollar-at`](references/quote-dollar-at.md) - Use "$@" for argument passing
- [`quote-command-substitution`](references/quote-command-substitution.md) - Quote command substitutions
- [`quote-brace-expansion`](references/quote-brace-expansion.md) - Use braces for variable clarity
- [`quote-here-documents`](references/quote-here-documents.md) - Use here documents for multi-line strings
- [`quote-glob-safety`](references/quote-glob-safety.md) - Control glob expansion explicitly

### 6. Functions & Structure (MEDIUM)

- [`func-main-pattern`](references/func-main-pattern.md) - Use main() function pattern
- [`func-single-purpose`](references/func-single-purpose.md) - Write single-purpose functions
- [`func-return-values`](references/func-return-values.md) - Use return values correctly
- [`func-documentation`](references/func-documentation.md) - Document functions with header comments
- [`func-avoid-aliases`](references/func-avoid-aliases.md) - Prefer functions over aliases

### 7. Testing & Conditionals (MEDIUM)

- [`test-double-brackets`](references/test-double-brackets.md) - Use [[ ]] for tests in bash
- [`test-arithmetic`](references/test-arithmetic.md) - Use (( )) for arithmetic comparisons
- [`test-explicit-empty`](references/test-explicit-empty.md) - Use explicit empty/non-empty string tests
- [`test-file-operators`](references/test-file-operators.md) - Use correct file test operators
- [`test-case-patterns`](references/test-case-patterns.md) - Use case for pattern matching

### 8. Performance (LOW-MEDIUM)

- [`perf-builtins-over-external`](references/perf-builtins-over-external.md) - Use builtins over external commands
- [`perf-avoid-subshells`](references/perf-avoid-subshells.md) - Avoid unnecessary subshells
- [`perf-process-substitution`](references/perf-process-substitution.md) - Use process substitution for temp files
- [`perf-read-files`](references/perf-read-files.md) - Read files efficiently
- [`perf-parameter-expansion`](references/perf-parameter-expansion.md) - Use parameter expansion for string operations
- [`perf-batch-operations`](references/perf-batch-operations.md) - Batch operations instead of loops

### 9. Style & Formatting (LOW)

- [`style-indentation`](references/style-indentation.md) - Use consistent indentation
- [`style-file-structure`](references/style-file-structure.md) - Follow consistent file structure
- [`style-comments`](references/style-comments.md) - Write useful comments


## How to Use

Read individual reference files for detailed explanations and code examples:

- [Section definitions](references/_sections.md) - Category structure and impact levels
- [Rule template](assets/templates/_template.md) - Template for adding new rules

## Reference Files

| File | Description |
|------|-------------|
| [AGENTS.md](AGENTS.md) | Complete compiled guide with all rules |
| [references/_sections.md](references/_sections.md) | Category definitions and ordering |
| [assets/templates/_template.md](assets/templates/_template.md) | Template for new rules |
| [metadata.json](metadata.json) | Version and reference information |

## Key Sources

- [Google Shell Style Guide](https://google.github.io/styleguide/shellguide.html)
- [ShellCheck](https://www.shellcheck.net/)
- [Greg's Wiki (wooledge.org)](https://mywiki.wooledge.org/)
- [POSIX Shell Specification](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html)

© pproenca · MIT · pproenca/dot-skills

Похожие скиллы

Все скиллы по теме «Языки программирования» →
bash-script-validator akin-ozer Скилл прогоняет bash и POSIX-скрипты через синтаксическую проверку, ShellCheck и собственные проверки безопасности. Пригодится перед CI. CX Codex +1 679установок bash-scripting Mindrally Скилл задаёт агенту правила написания Bash-скриптов: валидация ввода, обработка ошибок, переносимость. Пригодится, когда агент пишет деплой, бэкапы или cron-задачи. CX Codex +1 875установок bash-pro sickn33 Инструкции для агента по написанию защищённых Bash-скриптов для CI/CD и серверов с проверками через ShellCheck и Bats. CX Codex +1 966установок linux-shell-scripting zebbern Скилл с готовыми шаблонами bash-скриптов: бэкапы, мониторинг ресурсов, управление пользователями, разбор логов. Пригодится, когда агенту нужно написать рабочий скрипт, а не набросок. CX Codex +1 ★ 4 676звёзд репо bash-script-generator akin-ozer Скилл, который превращает задачу в готовый bash-скрипт: собирает требования, пишет код по шаблону и проверяет его. CX Codex +1 670установок bun-shell secondsky Скилл для работы с shell-скриптами на Bun: шаблонные литералы Bun.$, Bun.spawn, управление процессами и выводом. CX Codex +1 394установок

Из того же набора45

react-refactor Скилл с 40 правилами архитектурного рефакторинга React-проектов. Помогает декомпозировать крупные компоненты, выносить хуки и наводить порядок в модулях. CX Codex +1 776установок shadcn Скилл с 58 правилами для shadcn/ui: подсказывает агенту, как правильно ставить компоненты, писать формы и не ломать доступность. CX Codex +1 724установок chrome-extension-ui Набор правил по интерфейсу расширений Chrome: где ставить popup, где side panel, как сделать доступную навигацию и понятные состояния загрузки. CX Codex +1 719установок chrome-extension Скилл с 67 правилами по Chrome Extensions на Manifest V3. Пригодится, когда пишете service worker, content script или мигрируете с MV2. CX Codex +1 717установок refactor Набор из 43 правил рефакторинга по каталогу Мартина Фаулера и принципам Clean Code. Пригодится, когда агент правит чужой код и нужно, чтобы он делал это по понятным правилам. CX Codex +1 641установок react Скилл с 49 правилами React 19 и алгоритмом ревью кодовой базы. Пригодится при написании компонентов, миграции с React 18 и аудите репозитория. CX Codex +1 489установок tailwind-responsive-ui Скилл для Claude и других ИИ-редакторов: помогает переделывать интерфейсы на Tailwind CSS под мобильные и десктопные экраны. CX Codex +1 461установок tailwind-ui-refactor Скилл для рефакторинга HTML с классами Tailwind: подсказывает, как выстроить иерархию, отступы, типографику и цвет. Пригодится, когда верстаешь без дизайнера. CX Codex +1 458установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой