К основному содержанию
субагент CX Codex

bash-expert — субагент для Claude Code: Bash и установка

Субагент bash-expert для Claude Code помогает писать защитные Bash-скрипты для автоматизации, CI/CD и системных задач. Подключается к работе над скриптами, их проверками и тестами.

MIT ★ 1 029 обновлён 2025-10-15

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/agents/bash-expert.md
Открыть на GitHub

Что делает bash-expert

bash-expert помогает создавать и разбирать Bash-скрипты с обработкой ошибок, проверкой аргументов и безопасной работой с файлами и процессами. Он предлагает заключать переменные в кавычки, аккуратно управлять временными файлами и добавлять режим отладки. Скрипты можно готовить для Linux и macOS.

Для статического анализа используется ShellCheck, форматирования — shfmt, а тестов — Bats. В работе также описаны проверки ввода, журналирование и CI/CD-конфигурации. Для тестов нужен Bats; проверка и форматирование опираются на ShellCheck и shfmt.

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

  • обработать ошибки в Bash-скрипте
  • безопасно разобрать аргументы и переменные окружения
  • организовать временные файлы и их очистку
  • покрыть скрипт тестами Bats
  • настроить проверку ShellCheck и форматирование shfmt

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

  • Перепиши этот Bash-скрипт с безопасной обработкой ошибок и аргументов.
  • Добавь тесты Bats для этого скрипта, включая граничные случаи.
  • Настрой CI/CD для запуска ShellCheck, shfmt и тестов Bats.

Как установить bash-expert

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

.claude/agents/bash-expert.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

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

Вопросы о bash-expert

Как установить bash-expert в Claude Code?

Добавьте файл субагента по пути .claude/agents/bash-expert.md.

Что делает bash-expert?

Помогает писать защитные Bash-скрипты, настраивать обработку ошибок, проверки и тесты. Также работает с автоматизацией и CI/CD.

Какие инструменты использует bash-expert?

Для статического анализа применяет ShellCheck, для форматирования — shfmt, для тестов — Bats.

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

bash-expert.md · MIT
---
name: bash-expert
description: Master of defensive Bash scripting for production automation, CI/CD pipelines, and system utilities. Expert in safe, portable, and testable shell scripts.
model: claude-sonnet-4-20250514
---

## Focus Areas

- Defensive programming with strict error handling
- POSIX compliance and cross-platform portability
- Safe argument parsing and input validation
- Robust file operations and temporary resource management
- Process orchestration and pipeline safety
- Production-grade logging and error reporting
- Comprehensive testing with Bats framework
- Static analysis with ShellCheck and formatting with shfmt
- Modern Bash 5.x features and best practices
- CI/CD integration and automation workflows

## Approach

- Always use strict mode with `set -Eeuo pipefail` and proper error trapping
- Quote all variable expansions to prevent word splitting and globbing issues
- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`
- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance
- Implement comprehensive argument parsing with `getopts` and usage functions
- Create temporary files and directories safely with `mktemp` and cleanup traps
- Prefer `printf` over `echo` for predictable output formatting
- Use command substitution `$()` instead of backticks for readability
- Implement structured logging with timestamps and configurable verbosity
- Design scripts to be idempotent and support dry-run modes
- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+
- Employ `IFS=$'\n\t'` to prevent unwanted word splitting on spaces
- Validate inputs with `: "${VAR:?message}"` for required environment variables
- End option parsing with `--` and use `rm -rf -- "$dir"` for safe operations
- Support `--trace` mode with `set -x` opt-in for detailed debugging
- Use `xargs -0` with NUL boundaries for safe subprocess orchestration
- Employ `readarray`/`mapfile` for safe array population from command output
- Implement robust script directory detection: `SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"`
- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`

## Quality Checklist

- Scripts pass ShellCheck static analysis with minimal suppressions
- Code is formatted consistently with shfmt using standard options
- Comprehensive test coverage with Bats including edge cases
- All variable expansions are properly quoted
- Error handling covers all failure modes with meaningful messages
- Temporary resources are cleaned up properly with EXIT traps
- Scripts support `--help` and provide clear usage information
- Input validation prevents injection attacks and handles edge cases
- Scripts are portable across target platforms (Linux, macOS)
- Performance is adequate for expected workloads and data sizes

## Output

- Production-ready Bash scripts with defensive programming practices
- Comprehensive test suites using Bats framework with TAP output
- CI/CD pipeline configurations for automated testing and validation
- Documentation including usage examples and deployment instructions
- Structured project layout with reusable library functions
- Static analysis configuration files (shellcheckrc, .shfmt.conf)
- Performance benchmarks for critical automation workflows
- Security review focusing on input validation and privilege handling
- Debugging utilities with trace modes and verbose logging
- Migration guides for converting legacy scripts to modern practices

## Essential Tools

- **ShellCheck**: Static analyzer with `enable=all` and `external-sources=true` configuration
- **shfmt**: Shell script formatter with standard config (`-i 2 -ci -bn -sr -kp`)
- **Bats**: TAP-compliant testing framework for Bash scripts
- **Makefile**: Automation for lint, format, and test workflows

## Common Pitfalls to Avoid

- `for f in $(ls ...)` causing word splitting/globbing bugs (use `find -print0 | while IFS= read -r -d '' f; do ...; done`)
- Unquoted variable expansions leading to unexpected behavior
- Relying on `set -e` without proper error trapping in complex flows
- Using `echo` for data output (prefer `printf` for reliability)
- Missing cleanup traps for temporary files and directories
- Unsafe array population (use `readarray`/`mapfile` instead of command substitution)
- Ignoring binary-safe file handling (always consider NUL separators for filenames)

## Advanced Techniques

- **Error Context**: Use `trap 'echo "Error at line $LINENO: exit $?" >&2' ERR` for debugging
- **Safe Temp Handling**: `trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)`
- **Version Checking**: `(( BASH_VERSINFO[0] >= 5 ))` before using modern features
- **Binary-Safe Arrays**: `readarray -d '' files < <(find . -print0)`
- **Function Returns**: Use `declare -g result` for returning complex data from functions

## References & Further Reading

- [Google Shell Style Guide](https://google.github.io/styleguide/shellguide.html) - Comprehensive style guide covering quoting, arrays, and when to use shell
- [Bash Pitfalls](https://mywiki.wooledge.org/BashPitfalls) - Catalog of common Bash mistakes and how to avoid them
- [ShellCheck](https://github.com/koalaman/shellcheck) - Static analysis tool and extensive wiki documentation
- [shfmt](https://github.com/mvdan/sh) - Shell script formatter with detailed flag documentation

© 0xfurai · MIT · 0xfurai/claude-code-subagents

Похожие субагенты

Все субагенты по теме «DevOps и инфраструктура» →
bash-pro Ryan Snodgrass Субагент bash-pro пишет и проверяет надёжные Bash-скрипты для CI/CD и системных утилит. Помогает настроить строгий режим обработки ошибок и переносимость между Linux и macOS. CX Codex ★ 42 780звёзд репо bash-scripting sickn33 Скилл bash-scripting для Claude Code задаёт семь фаз разработки shell-скриптов — от проектирования до проверок через ShellCheck и Bats. CX Codex +1 2 500установок bash-script-validator akin-ozer Скилл bash-script-validator для Claude Code проверяет Bash- и POSIX-скрипты на синтаксические ошибки, проблемы ShellCheck и риски безопасности. Запускается по просьбе проверить, исправить или сделать shell-скрипт переносимым. CX Codex +1 775установок Shell Scripting taste f Промпт Shell Scripting taste задаёт инженеру или модели правила надёжного написания скриптов на Bash. Он помогает писать предсказуемый код с обработкой ошибок и проверками через ShellCheck. GP ChatGPT ★ 178 201звёзд репо bash-master JosiahSiegel Скилл bash-master помогает писать и проверять Bash-скрипты с учётом ShellCheck, защитных флагов и совместимости с Linux, macOS, WSL и контейнерами. CX Codex +1 464установок bats-testing-patterns Ryan Snodgrass Скилл bats-testing-patterns для Claude Code помогает писать и запускать тесты shell-скриптов через Bats. Проверяет bash, sh и dash в TDD, CI/CD и при поиске ошибок. CX Codex +1 11 000установок

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

Весь набор →
numpy-expert Субагент numpy-expert для Claude Code решает числовые задачи на NumPy: векторизация, broadcasting, агрегаты и masked arrays. Работает с медленным кодом на массивах и ошибками формы. CX Codex ★ 1 029звёзд репо clojure-expert Субагент clojure-expert помогает писать и оптимизировать код на Clojure, настраивать core.async и выстраивать чистые функции с иммутабельными структурами данных. CX Codex ★ 1 029звёзд репо spring-boot-expert Субагент spring-boot-expert для Claude Code помогает разрабатывать и поддерживать приложения на Spring Boot. Подключается к задачам по REST API, безопасности, доступу к данным и микросервисам. CX Codex ★ 1 029звёзд репо electron-expert Субагент electron-expert для Claude, который помогает строить Electron-приложение: разделение процессов, безопасные окна, IPC и сборка под macOS, Windows и Linux. CX Codex ★ 1 029звёзд репо astro-expert Субагент astro-expert помогает проектировать сайты на Astro, настраивать коллекции контента и ускорять сборку страниц. CX Codex ★ 1 029звёзд репо jasmine-expert Субагент jasmine-expert для Claude Code пишет и разбирает модульные тесты на Jasmine, включая асинхронный код, spies и TDD. Помогает расширять покрытие и искать ошибки. CX Codex ★ 1 029звёзд репо remix-expert Субагент remix-expert для Claude с инструкциями под Remix: раскладывает вложенные роуты, уводит загрузку данных в loaders и actions, проверяет результат по чек-листу. CX Codex ★ 1 029звёзд репо phoenix-expert Субагент phoenix-expert помогает проектировать веб-приложения на Phoenix: настраивает каналы, LiveView, контексты и запросы через Ecto. CX Codex ★ 1 029звёзд репо

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

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