Skip to main content
rule CX Codex

bash · microsoft — Claude Code rule: Bash scripting conventions

A rule enforcing consistent Bash script structure: strict mode, main() pattern, formatting, error handling, and Microsoft copyright headers.

MIT ★ 1,627 updated 2026-10-25

Install into GitHub Copilot · Manually: put the files in place All methods and platforms ↓
.github/instructions/bash.instructions.md
Open on GitHub

What bash does

The rule applies to all .sh files in the project. Scripts follow Bash 5.x conventions with mandatory set -euo pipefail, a main() function called at the end, and #!/usr/bin/env bash shebang. Environment variables use UPPER_SNAKE_CASE, local variables lower_snake_case, 2-space indentation, lines kept under 80 characters. Every file starts with a Microsoft copyright header and MIT license.

Inside scripts: tests via [[ ... ]], quoted variable expansion "${var}", arrays through declare -a, command checks via command -v. No #!/bin/bash, no tabs, no backticks for substitution. If the project has copyright validation in package.json, CI checks headers automatically.

What it helps with

  • uniform structure for Bash scripts across the repository
  • error detection through strict mode and pipefail
  • Microsoft copyright headers in every .sh file
  • ShellCheck compliance and CI-ready formatting
  • safe handling of variables and arguments

Example prompts for the agent

  • Write a deploy.sh script for Azure deployment with validation of ENVIRONMENT and RESOURCE_GROUP variables
  • Add logging functions log() and err() to the validate.sh script
  • Fix backup.sh according to the bash rule: add strict mode and a Microsoft copyright header

How to install bash

Manually: put the files in place

.github/instructions/bash.instructions.md

The applyTo field sets which files it applies to

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about bash

How to install the bash rule in Claude Code?

Place the file in .claude/rules/bash.md — Claude Code will apply the rule to all .sh files.

What does the bash rule do?

It enforces conventions for Bash scripts: main() structure, strict mode, formatting, error handling, and mandatory Microsoft copyright headers.

Which shebang does the bash rule require?

Only #!/usr/bin/env bash for cross-system portability. #!/bin/bash is forbidden.

Source text

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

Similar IDE rules

All IDE rules for DevOps and infrastructure →

bash by other authors comes first.

bash sanjeed5 A Cursor rule for Bash scripts that sets guidance on errors, quoting, variables, and code structure. Use it when these conventions should apply across a project. CX Codex +1 ★ 3,589repo stars bash-scripting Mindrally The bash-scripting skill gives the agent rules for writing Bash scripts: input validation, error handling, portability. Useful when the agent writes deploy, backup or cron tasks. CX Codex +1 934installs bash-master JosiahSiegel bash-master guides bash scripting with ShellCheck linting, error-trapping preambles, and cross-platform handling for Linux, macOS, WSL, and containers. CX Codex +1 464installs bash-script-validator akin-ozer bash-script-validator is a Claude Code skill that checks Bash and POSIX shell scripts for syntax faults, ShellCheck findings, and security issues. It activates for script reviews, linting, fixes, or portability requests. CX Codex +1 775installs bash-pro rmyndharis The bash-pro Claude Code skill guides Bash scripting for automation, CI/CD, and system tasks. It helps structure argument handling, error recovery, and script checks. CX Codex +1 123installs bash-linux davila7 bash-linux — a Bash reference skill for macOS and Linux: command chaining, files, processes, error handling. Useful when the agent edits shell scripts or digs through logs. CX Codex +1 215installs shell-bash miles990 shell-bash is a Claude Code skill that provides Bash script patterns for parsing arguments, checking paths, and working with strings and arrays. Use these patterns to automate terminal tasks and write system scripts. CX Codex +1 112installs

From the same set148

The whole set →
pester This rule guides Claude Code in writing PowerShell tests with Pester. Use it to keep test files, mocks, and cleanup consistent with the repository. CX Codex +1 ★ 1,627repo stars typescript-doc-comments typescript-doc-comments — a Claude Code rule for writing TypeScript documentation comments following the TSDoc standard. Describes function behavior, constraints, and intent that the type signature alone cannot express. CX Codex +1 ★ 1,627repo stars engagement-reporting engagement-reporting generates source-backed weekly project engagement reports and prepares optional Outlook email drafts. CX Codex +1 ★ 1,627repo stars hve-builder hve-builder is a Claude Code skill for creating or revising prompts, instructions, agents, and skills, or for read-only reviews and mechanical validation without changing files. CX Codex +1 ★ 1,627repo stars incident-response incident-response guides SRE and operations teams through Azure incident triage, diagnostic query writing, mitigation plans, and root cause documentation. CX Codex +1 ★ 1,627repo stars terraform Sets conventions for Terraform files, resource names, modules, and expressions. It applies to .tf, .tfvars, and files under terraform/. CX Codex +1 ★ 1,627repo stars adr-byo-template adr-byo-template defines the contract for bring-your-own ADR templates: how project config resolves and what fields a template must declare for the ADR Creator to accept it. CX Codex +1 ★ 1,627repo stars pptx pptx defines directory structure, YAML schemas, and layout constraints for building PowerPoint slide decks with AI agents. CX Codex +1 ★ 1,627repo stars

Project sponsors

Companies that keep this analytics open