---
title: "Create Hook Command"
description: "Analyze the project, suggest practical hooks, and create them with proper testing."
type: skill
canonical_url: https://claudary.paisolsolutions.com/skills/skill-511
source: "Claudary"
difficulty: intermediate
author: "Claude Code Knowledge Pack"
date: 2026-07-10T11:45:00.591Z
license: CC-BY-4.0
attribution: "Create Hook Command — Claudary (https://claudary.paisolsolutions.com/skills/skill-511)"
---

# Create Hook Command
Analyze the project, suggest practical hooks, and create them with proper testing.

## Overview

---
name: create-hook
description: Create and configure git hooks with intelligent project analysis, suggestions, and automated testing
argument-hint: Optional hook type or description of desired behavior
---

# Create Hook Command

Analyze the project, suggest practical hooks, and create them with proper testing.

## Your Task (/create-hook)

1. **Analyze environment** - Detect tooling and existing hooks
2. **Suggest hooks** - Based on your project configuration
3. **Configure hook** - Ask targeted questions and create the script
4. **Test & validate** - Ensure the hook works correctly

## Your Workflow

### 1. Environment Analysis & Suggestions

Automatically detect the project tooling and suggest relevant hooks:

**When TypeScript is detected (`tsconfig.json`):**

- PostToolUse hook: "Type-check files after editing"
- PreToolUse hook: "Block edits with type errors"

**When Prettier is detected (`.prettierrc`, `prettier.config.js`):**

- PostToolUse hook: "Auto-format files after editing"
- PreToolUse hook: "Require formatted code"

**When ESLint is detected (`.eslintrc.*`):**

- PostToolUse hook: "Lint and auto-fix after editing"
- PreToolUse hook: "Block commits with linting errors"

**When package.json has scripts:**

- `test` script → "Run tests before commits"
- `build` script → "Validate build before commits"

**When a git repository is detected:**

- PreToolUse/Bash hook: "Prevent commits with secrets"
- PostToolUse hook: "Security scan on file changes"

**Decision Tree:**

```
Project has TypeScript? → Suggest type checking hooks
Project has formatter? → Suggest formatting hooks
Project has tests? → Suggest test validation hooks
Security sensitive? → Suggest security hooks
+ Scan for additional patterns and suggest custom hooks based on:
  - Custom scripts in package.json
  - Unique file patterns or extensions
  - Development workflow indicators
  - Project-specific tooling configurations
```

### 2. Hook Configuration

Start by asking: **"What should this hook do?"** and offer relevant suggestions from your analysis.

Then understand the context from the user's description and **only ask about details you're unsure about**:

1. **Trigger timing**: When should it run?
   - `PreToolUse`: Before file operations (can block)
   - `PostToolUse`: After file operations (feedback/fixes)
   - `UserPromptSubmit`: Before processing requests
   - Other event types as needed

2. **Tool matcher**: Which tools should trigger it? (`Write`, `Edit`, `Bash`, `*` etc)

3. **Scope**: `global`, `project`, or `project-local`

4. **Response approach**:
   - **Exit codes only**: Simple (exit 0 = success, exit 2 = block in PreToolUse)
   - **JSON response**: Advanced control (blocking, context, decisions)
   - Guide based on complexity: simple pass/fail → exit codes, rich feedback → JSON

5. **Blocking behavior** (if relevant): "Should this stop operations when issues are found?"
   - PreToolUse: Can block operations (security, validation)
   - PostToolUse: Usually provide feedback only

6. **Claude integration** (CRITICAL): "Should Claude Code automatically see and fix issues this hook detects?"
   - If YES: Use `additionalContext` for error communication
   - If NO: Use `suppressOutput: true` for silent operation

7. **Context pollution**: "Should successful operations be silent to avoid noise?"
   - Recommend YES for formatting, routine checks
   - Recommend NO for security alerts, critical errors

8. **File filtering**: "What file types should this hook process?"

### 3. Hook Creation

You should:

- **Create hooks directory**: `~/.claude/hooks/` or `.claude/hooks/` based on scope
- **Generate script**: Create hook script with:
  - Proper shebang and executable permissions
  - Project-specific commands (use detected config paths)
  - Comments explaining the hook's purpose
- **Update settings**: Add hook configuration to appropriate settings.json
- **Use absolute paths**: Avoid relative paths to scripts and executables. Use `$CLAUDE_PROJECT_DIR` to reference project root
- **Offer validation**: Ask if the user wants you to test the hook

**Key Implementation Standards:**

- Read JSON from stdin (never use argv)
- Use top-level `additionalContext`/`systemMessage` for Claude communication
- Include `suppressOutput: true` for successful operations
- Provide specific error counts and actionable feedback
- Focus on changed files rather than entire codebase
- Support common development workflows

**⚠️ CRITICAL: Input/Output Format**

This is where most hook implementations fail. Pay extra attention to:

- **Input**: Reading JSON from stdin correctly (not argv)
- **Output**: Using correct top-level JSON structure for Claude communication
- **Documentation**: Consulting official docs for exact schemas when in doubt

### 4. Testing & Validation

**CRITICAL: Test both happy and sad paths:**

**Happy Path Testing:**

1. **Test expected success scenario** - Create conditions where hook should pass
   - _Examples_: TypeScript (valid code), Linting (formatted code), Security (safe commands)

**Sad Path Testing:** 2. **Test expected failure scenario** - Create conditions where hook should fail/warn

- _Examples_: TypeScript (type errors), Linting (unformatted code), Security (dangerous operations)

**Verification Steps:** 3. **Verify expected behavior**: Check if it blocks/warns/provides context as intended

**Example Testing Process:**

- For a hook preventing file deletion: Create a test file, attempt the protected action, and verify the hook prevents it

**If Issues Occur, you should:**

- Check hook registration in settings
- Verify script permissions (`chmod +x`)
- Test with simplified version first
- Debug with detailed hook execution analysis

## Hook Templates

### Type Checking (PostToolUse)

```
#!/usr/bin/env node
// Read stdin JSON, check .ts/.tsx files only
// Run: npx tsc --noEmit --pretty
// Output: JSON with additionalContext for errors
```

### Auto-formatting (PostToolUse)

```
#!/usr/bin/env node
// Read stdin JSON, check supported file types
// Run: npx prettier --write [file]
// Output: JSON with suppressOutput: true
```

### Security Scanning (PreToolUse)

```bash
#!/bin/bash
# Read stdin JSON, check for secrets/keys
# Block if dangerous patterns found
# Exit 2 to block, 0 to continue
```

_Complete templates available at: <https://docs.claude.com/en/docs/claude-code/hooks#examples>_

## Quick Reference

**📖 Official Docs**: <https://docs.claude.com/en/docs/claude-code/hooks.md>

**Common Patterns:**

- **stdin input**: `JSON.parse(process.stdin.read())`
- **File filtering**: Check extensions before processing
- **Success response**: `{continue: true, suppressOutput: true}`
- **Error response**: `{continue: true, additionalContext: "error details"}`
- **Block operation**: `exit(2)` in PreToolUse hooks

**Hook Types by Use Case:**

- **Code Quality**: PostToolUse for feedback and fixes
- **Security**: PreToolUse to block dangerous operations
- **CI/CD**: PreToolUse to validate before commits
- **Development**: PostToolUse for automated improvements

**Hook Execution Best Practices:**

- **Hooks run in parallel** according to official documentation
- **Design for independence** since execution order isn't guaranteed
- **Plan hook interactions carefully** when multiple hooks affect the same files

## Success Criteria

✅ **Hook created successfully when:**

- Script has executable permissions
- Registered in correct settings.json
- Responds correctly to test scenarios
- Integrates properly with Claude for automated fixes
- Follows project conventions and detected tooling

**Result**: The user gets a working hook that enhances their development workflow with intelligent automation and quality checks.

---

> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
> Use this file to discover all available pages before exploring further.

# Automate workflows with hooks

> Run shell commands automatically when Claude Code edits files, finishes tasks, or needs input. Format code, send notifications, validate commands, and enforce project rules.

Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide deterministic control over Claude Code's behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools.

For decisions that require judgment rather than deterministic rules, you can also use [prompt-based hooks](#prompt-based-hooks) or [agent-based hooks](#agent-based-hooks) that use a Claude model to evaluate conditions.

For other ways to extend Claude Code, see [skills](/en/skills) for giving Claude additional instructions and executable commands, [subagents](/en/sub-agents) for running tasks in isolated contexts, and [plugins](/en/plugins) for packaging extensions to share across projects.

<Tip>
  This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](/en/hooks).
</Tip>

## Set up your first hook

The fastest way to create a hook is through the `/hooks` interactive menu in Claude Code. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.

<Steps>
  <Step title="Open the hooks menu">
    Type `/hooks` in the Claude Code CLI. You'll see a list of all available hook events, plus an option to disable all hooks. Each event corresponds to a point in Claude's lifecycle where you can run custom code. Select `Notification` to create a hook that fires when Claude needs your attention.
  </Step>

  <Step title="Configure the matcher">
    The menu shows a list of matchers, which filter when the hook fires. Set the matcher to `*` to fire on all notification types. You can narrow it later by changing the matcher to a specific value like `permission_prompt` or `idle_prompt`.
  </Step>

  <Step title="Add your command">
    Select `+ Add new hook…`. The menu prompts you for a shell command to run when the event fires. Hooks run any shell command you provide, so you can use your platform's built-in notification tool. Copy the command for your OS:

    <Tabs>
      <Tab title="macOS">
        Uses [`osascript`](https://ss64.com/mac/osascript.html) to trigger a native macOS notification through AppleScript:

        ```
        osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'
        ```
      </Tab>

      <Tab title="Linux">
        Uses `notify-send`, which is pre-installed on most Linux desktops with a notification daemon:

        ```
        notify-send 'Claude Code' 'Claude Code needs your attention'
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        Uses PowerShell to show a native message box through .NET's Windows Forms:

        ```
        powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')"
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Choose a storage location">
    The menu asks where to save the hook configuration. Select `User settings` to store it in `~/.claude/settings.json`, which applies the hook to all your projects. You could also choose `Project settings` to scope it to the current project. See [Configure hook location](#configure-hook-location) for all available scopes.
  </Step>

  <Step title="Test the hook">
    Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.
  </Step>
</Steps>

## What you can automate

Hooks let you run code at key points in Claude Code's lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](/en/hooks#hook-lifecycle).

Each example includes a ready-to-use configuration block that you add to a [settings file](#configure-hook-location). The most common patterns:

- [Get notified when Claude needs input](#get-notified-when-claude-needs-input)
- [Auto-format code after edits](#auto-format-code-after-edits)
- [Block edits to protected files](#block-edits-to-protected-files)
- [Re-inject context after compaction](#re-inject-context-after-compaction)

### Get notified when Claude needs input

Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal.

This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform's native notification command. Add this to `~/.claude/settings.json`, or use the [interactive walkthrough](#set-up-your-first-hook) above to configure it with `/hooks`:

<Tabs>
  <Tab title="macOS">
    ```json  theme={null}
    {
      "hooks": {
        "Notification": [
          {
            "matcher": "",
            "hooks": [
              {
                "type": "command",
                "command": "osascript -e 'display notification \\"Claude Code needs your attention\\" with title \\"Claude Code\\"'"
              }
            ]
          }
        ]
      }
    }
    ```
  </Tab>

  <Tab title="Linux">
    ```json  theme={null}
    {
      "hooks": {
        "Notification": [
          {
            "matcher": "",
            "hooks": [
              {
                "type": "command",
                "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
              }
            ]
          }
        ]
      }
    }
    ```
  </Tab>

  <Tab title="Windows (PowerShell)">
    ```json  theme={null}
    {
      "hooks": {
        "Notification": [
          {
            "matcher": "",
            "hooks": [
              {
                "type": "command",
                "command": "powershell.exe -Command \\"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\\""
              }
            ]
          }
        ]
      }
    }
    ```
  </Tab>
</Tabs>

### Auto-format code after edits

Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.github.io/jq/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:

``

---

Source: [Claudary](https://claudary.paisolsolutions.com/skills/skill-511) · https://claudary.paisolsolutions.com
