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

bash · microsoft — правило для Claude Code: конвенции Bash-скриптов

Правило задаёт единые конвенции для Bash-скриптов: strict mode, структуру с main(), форматирование, обработку ошибок и copyright-заголовки Microsoft.

MIT ★ 1 627 обновлён 2026-10-25

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/bash.instructions.md
Открыть на GitHub

Что делает bash

Правило применяется ко всем .sh файлам проекта. Скрипты пишутся под Bash 5.x с обязательным set -euo pipefail, функцией main() в конце и шебангом #!/usr/bin/env bash. Переменные окружения — в UPPER_SNAKE_CASE, локальные — в lower_snake_case, отступы 2 пробела, строки ≤ 80 символов. Каждый файл должен начинаться с copyright-заголовка Microsoft и лицензии MIT.

Внутри скриптов: тесты через [[ ... ]], расширение переменных в кавычках "${var}", массивы через declare -a, проверка команд через command -v. Без #!/bin/bash, без табуляции, без бэктиков для подстановки. Если в проекте настроена валидация copyright через package.json, CI проверяет заголовки автоматически.

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

  • единообразие структуры Bash-скриптов в репозитории
  • отлов ошибок через strict mode и pipefail
  • copyright-заголовки Microsoft в каждом .sh файле
  • соблюдение ShellCheck и форматирование под CI
  • безопасная работа с переменными и аргументами

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

  • Напиши скрипт deploy.sh для деплоя в Azure с проверкой переменных ENVIRONMENT и RESOURCE_GROUP
  • Добавь функцию логирования log() и err() в скрипт validate.sh
  • Исправь backup.sh по правилу bash: добавь strict mode и copyright-заголовок Microsoft

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

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

.github/instructions/bash.instructions.md

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Вопросы о bash

Как установить правило bash в Claude Code?

Положи файл в .claude/rules/bash.md — Claude Code применит правило ко всем .sh файлам.

Что делает правило bash?

Задаёт конвенции для Bash-скриптов: структуру с main(), strict mode, форматирование, обработку ошибок и обязательные copyright-заголовки Microsoft.

Какой shebang требует правило bash?

Только #!/usr/bin/env bash для переносимости между системами. #!/bin/bash запрещён.

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

bash.instructions.md · MIT
---
applyTo: '**/*.sh'
description: 'Bash script authoring conventions'
---

# Bash Script Instructions

These instructions define conventions for authoring Bash scripts in this repository. Scripts follow Bash 5.x conventions with strict error handling and ShellCheck compliance.

## Script Structure

Scripts follow a consistent structure with shebang, header comment, strict mode, and a main function pattern.

<!-- <template-script-structure> -->
```bash
#!/usr/bin/env bash
#
# script-name.sh
# Brief description of what this script does

set -euo pipefail

main() {
  # Script logic here
  echo "Executing..."
}

main "$@"
```
<!-- </template-script-structure> -->

### Shebang

Use `#!/usr/bin/env bash` for portability across systems.

### Strict Mode

Enable strict error handling at the top of every script:

```bash
set -euo pipefail
```

This configuration:

* `-e`: Exits immediately on command failure
* `-u`: Treats unset variables as errors
* `-o pipefail`: Propagates pipeline failures

### Main Function Pattern

Encapsulate script logic in a `main()` function called at the end. This pattern:

* Ensures all functions are defined before use
* Supports sourcing scripts for testing
* Provides clear entry point

## Copyright Headers

Every `.sh` file requires a copyright header immediately after the shebang line.

Two required lines:

* `# Copyright (c) Microsoft Corporation.`
* `# SPDX-License-Identifier: MIT`

Placement: after `#!/usr/bin/env bash`, before any other content.

CI validates copyright headers through the repository's copyright validation script, if one is configured. Check `package.json` for a copyright validation command.

<!-- <example-copyright-header> -->
```bash
#!/usr/bin/env bash
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT
#
# script-name.sh
# Brief description of script purpose

set -euo pipefail
```
<!-- </example-copyright-header> -->

## Formatting and Style

### Indentation and Line Length

* Use 2 spaces for indentation, never tabs
* Limit lines to 80 characters when practical
* Long commands use backslash continuation

```bash
az resource show \
  --resource-group "$RESOURCE_GROUP_NAME" \
  --name "$RESOURCE_NAME" \
  --query id \
  --output tsv
```

### Control Structures

Place `then` and `do` on the same line as their control keyword:

```bash
if [[ -n "${VAR:-}" ]]; then
  echo "Variable is set"
fi

for item in "${items[@]}"; do
  process "$item"
done
```

### Conditionals and Tests

* Use `[[ ... ]]` instead of `[ ... ]` or `test`
* Use `(( ... ))` for arithmetic operations

```bash
if [[ "${ENVIRONMENT}" == "prod" ]]; then
  echo "Production environment"
fi

if (( count > 10 )); then
  echo "Count exceeds threshold"
fi
```

## Variables and Naming

### Naming Conventions

| Type                  | Convention                       | Example                  |
|-----------------------|----------------------------------|--------------------------|
| Environment variables | UPPER_SNAKE_CASE                 | `RESOURCE_GROUP_NAME`    |
| Constants             | UPPER_SNAKE_CASE with `readonly` | `readonly MAX_RETRIES=3` |
| Local variables       | lower_snake_case                 | `local file_path`        |
| Function names        | lower_snake_case                 | `validate_input()`       |

### Variable Expansion

* Use braces for clarity: `"${var}"` over `"$var"`
* Quote all variable expansions unless word splitting is intentional
* Use command substitution with `$()`: never backticks

```bash
# Variable with default
ENVIRONMENT="${ENVIRONMENT:-dev}"

# Required variable check
if [[ -z "${REQUIRED_VAR:-}" ]]; then
  echo "ERROR: REQUIRED_VAR must be set" >&2
  exit 1
fi
```

### Arrays

Use arrays for lists of elements:

```bash
declare -a files=("file1.txt" "file2.txt" "file3.txt")

for file in "${files[@]}"; do
  process "$file"
done
```

## Functions

Define functions before use. Use `local` for function-scoped variables.

```bash
log() {
  local message="$1"
  printf "========== %s ==========\n" "$message"
}

err() {
  local message="$1"
  printf "ERROR: %s\n" "$message" >&2
  exit 1
}

validate_input() {
  local input="$1"
  if [[ -z "${input}" ]]; then
    err "Input cannot be empty"
  fi
}
```

## Error Handling

### Error Functions

Implement consistent error reporting:

```bash
err() {
  printf "ERROR: %s\n" "$1" >&2
  exit 1
}
```

### Command Validation

Check for required commands before use:

```bash
if ! command -v "az" &>/dev/null; then
  err "'az' command is required but not installed"
fi
```

### Error Visibility

Allow commands to fail naturally with their native error messages. Avoid redirecting stderr to `/dev/null` unless errors are genuinely irrelevant. Let tools display their built-in error information.

## Comments

Keep comments minimal. Add them only when logic requires explanation:

* Complex regex patterns
* Non-obvious conditionals
* Workarounds with context

```bash
# Match semantic version pattern: major.minor.patch
if [[ "${version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Valid version"
fi
```

Document environment variables at the top of scripts that require them:

```bash
## Required Environment Variables:
# ENVIRONMENT       - Target environment (dev, prod)
# RESOURCE_GROUP    - Azure resource group name

## Optional Environment Variables:
# DEBUG             - Enable verbose output when set
```

## Usage Functions

Scripts with arguments include a usage function:

```bash
usage() {
  echo "Usage: ${0##*/} [OPTIONS]"
  echo ""
  echo "Options:"
  echo "  --help, -h    Show this help message"
  echo "  --verbose     Enable verbose output"
  exit 1
}
```

## Argument Parsing

Use `case` statements for argument handling:

```bash
while [[ $# -gt 0 ]]; do
  case "$1" in
    --verbose)
      VERBOSE=true
      shift
      ;;
    --output)
      if [[ -z "${2:-}" || "$2" == --* ]]; then
        echo "Error: --output requires an argument" >&2
        usage
      fi
      OUTPUT_FILE="$2"
      shift 2
      ;;
    --help|-h)
      usage
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage
      ;;
  esac
done
```

## File Operations

Create directories safely and handle paths properly:

```bash
mkdir -p "$(dirname "$OUTPUT_FILE")"
```

Before sourcing repository-managed CI configuration, apply the authority
contract in [Repository-Managed CI Configuration](#repository-managed-ci-configuration).
File existence and path quoting do not establish authorization.

## Security Practices

### Repository-Managed CI Configuration

Treat sourced configuration as executable code. For repository-managed CI
configuration, authority comes from the reviewed repository revision and the
resulting checkout. Only reviewed changes present at the expected path in that
checkout are authorized. Path or symbolic-link substitution and post-checkout
modification invalidate that authority.

Fail closed when the authorized configuration is absent. Do not source a
substitute or continue with an implicit default.

```bash
# authorized-ci-configuration
readonly ci_config="${REPOSITORY_ROOT}/.ci/config.sh"

if [[ ! -f "${ci_config}" ]]; then
  echo "ERROR: Authorized CI configuration is absent" >&2
  exit 1
fi

# Source only after establishing authority from the reviewed checkout.
source "${ci_config}"
```

Operator-managed, user-selected, and externally acquired configuration need
separate owner decisions. Do not apply this CI authority contract to those
classes without an established policy.

### Variable Quoting

Quote variables to prevent word splitting and command injection:

```bash
# Correct
rm -f "${temp_file}"
grep "${pattern}" "${file}"

# Avoid
rm -f $temp_file
grep $pattern $file
```

### File Permissions

Set appropriate permissions for sensitive files:

```bash
chmod 0600 "${HOME}/.kube/config"
```

### Checksum Verification

Verify downloaded files before execution:

```bash
EXPECTED_SHA256="abc123..."
if ! echo "${EXPECTED_SHA256} ${downloaded_file}" | sha256sum -c --quiet -; then
  echo "ERROR: Checksum verification failed" >&2
  rm "${downloaded_file}"
  exit 1
fi
```

## ShellCheck Compliance

All scripts pass ShellCheck validation. Use the VS Code problems panel or run ShellCheck directly:

```bash
shellcheck script.sh
```

When a specific rule needs suppression, add a directive with justification:

```bash
# shellcheck disable=SC2034  # Variable used by sourced script
EXPORTED_CONFIG="value"
```

## Azure CLI Patterns

When working with Azure CLI commands:

### Output Handling

* Use `--output tsv` for single values in scripts
* TSV output returns empty strings for null values (not the string "null")
* Use `--query` with JMESPath for filtering results

```bash
resource_id=$(az resource show \
  --resource-group "$RESOURCE_GROUP" \
  --name "$RESOURCE_NAME" \
  --resource-type "Microsoft.Storage/storageAccounts" \
  --query id \
  --output tsv)

if [[ -z "${resource_id}" ]]; then
  err "Resource not found"
fi
```

### Conditional Command Arguments

Build commands with arrays when arguments are conditional:

```bash
az_cmd=("az" "connectedk8s" "connect"
  "--name" "$RESOURCE_NAME"
  "--resource-group" "$RESOURCE_GROUP"
)

if [[ "${AUTO_UPGRADE:-true}" == "false" ]]; then
  az_cmd+=("--disable-auto-upgrade")
fi

"${az_cmd[@]}"
```

© microsoft · MIT · microsoft/hve-core

Похожие правила IDE

Все правила IDE по теме «DevOps и инфраструктура» →

Сначала — bash от других авторов.

bash sanjeed5 Правило задаёт стиль для Bash-скриптов: обработка ошибок, кавычки, переменные и структура кода. Подходит для проектов, где скрипты проходят через Cursor. CX Codex +1 ★ 3 589звёзд репо bash-scripting Mindrally Скилл bash-scripting для Claude Code задаёт агенту правила написания Bash-скриптов: валидация ввода, обработка ошибок, переносимость. Агент пишет деплой, бэкапы и cron-задачи по стандартам POSIX с явными проверками кодов возврата. CX Codex +1 934установок bash-master JosiahSiegel Скилл bash-master помогает писать и проверять Bash-скрипты с учётом ShellCheck, защитных флагов и совместимости с Linux, macOS, WSL и контейнерами. CX Codex +1 464установок bash-script-validator akin-ozer Скилл bash-script-validator для Claude Code проверяет Bash- и POSIX-скрипты на синтаксические ошибки, проблемы ShellCheck и риски безопасности. Запускается по просьбе проверить, исправить или сделать shell-скрипт переносимым. CX Codex +1 775установок bash-pro rmyndharis Скилл bash-pro для Claude Code помогает писать и проверять Bash-скрипты для автоматизации, CI/CD и системных задач. Подсказывает, как защитить скрипт от небезопасной обработки аргументов и ошибок. CX Codex +1 123установок bash-linux davila7 Скилл bash-linux для Claude Code — справочник по Bash в macOS и Linux: команды, файлы, процессы и обработка ошибок. Помогает править скрипты и разбирать логи. CX Codex +1 215установок shell-bash miles990 Скилл shell-bash для Claude Code подсказывает шаблоны Bash-скриптов: от разбора аргументов до работы с массивами. Шаблоны помогают автоматизировать задачи в терминале и писать системные скрипты. CX Codex +1 112установок

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

Весь набор →
pester Правило задаёт соглашения для тестов PowerShell на Pester. Оно помогает Claude Code оформлять тестовые файлы и изолировать проверки по структуре репозитория. CX Codex +1 ★ 1 627звёзд репо typescript-doc-comments Правило typescript-doc-comments для написания документирующих комментариев в TypeScript по стандарту TSDoc. Помогает описать поведение и ограничения функций, типов и компонентов так, чтобы вызывающий код не ошибся. CX Codex +1 ★ 1 627звёзд репо engagement-reporting Скилл engagement-reporting формирует еженедельные отчёты о ходе проекта с опорой на первоисточники и создаёт черновики писем в Outlook. CX Codex +1 ★ 1 627звёзд репо hve-builder Скилл hve-builder помогает создавать и дорабатывать промпты, инструкции, агентов и другие скиллы. Он также проводит проверку качества или механическую валидацию без изменения файлов. CX Codex +1 ★ 1 627звёзд репо incident-response Скилл incident-response помогает дежурным инженерам и SRE расследовать инциденты в Azure: оценивать критичность, писать диагностические запросы и готовить отчёты о причинах сбоя. CX Codex +1 ★ 1 627звёзд репо terraform Задаёт соглашения для Terraform-кода: структуру файлов, именование ресурсов и переменных, работу с модулями и выражениями. Применяется к .tf и .tfvars. CX Codex +1 ★ 1 627звёзд репо adr-byo-template Правило adr-byo-template задаёт контракт для собственных шаблонов ADR: как резолвится конфиг проекта и что должен объявить шаблон, чтобы ADR Creator его принял. CX Codex +1 ★ 1 627звёзд репо pptx Задаёт структуру каталогов, форматы YAML и правила верстки для сборки презентаций PowerPoint с помощью агентов и python-pptx. CX Codex +1 ★ 1 627звёзд репо

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

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