Getting started

Introduction

Claude Code hooks run shell commands, HTTP endpoints, MCP tools, prompts, or agents at lifecycle events. This sheet covers matchers, output, and decisions.

Anatomy

flowchart LR
  accTitle: Hook anatomy
  accDescr: PreToolUse uses Edit|Write; Notification an empty matcher.
  subgraph event ["`**Event**`"]
    direction TB
    PreToolUse["`**PreToolUse**<br>before a tool call`"]
    Notification["`**Notification**<br>Claude needs input`"]
  end
  subgraph matcher ["`**Matcher group**`"]
    direction TB
    EditWrite["`**Edit|Write**<br>either tool`"]
    Empty["`**#quot;#quot;**<br>every event`"]
  end
  subgraph handler ["`**Handler**`"]
    direction TB
    Command["`**command**<br>runs a shell command`"]
  end
  PreToolUse --> EditWrite --> Command
  Notification --> Empty --> Command
Hook anatomy

A hook event fires at a lifecycle point. Its matcher group filters the event, then matching handlers run in parallel.

See: Hooks reference

First hook

{
  "hooks": {
    "Notification": [
      {
        "matcher": "permission_prompt",
        "hooks": [
          { "type": "command",
            "command": "notify-send 'Claude Code' 'Needs input'" }
        ]
      }
    ]
  }
}

Run /hooks to confirm the hook loaded. On macOS, use osascript instead of notify-send.

See: Set up your first hook

Everyday hooks

Format after edits

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/format.sh" }
        ]
      }
    ]
  }
}

The script reads .tool_input.file_path with jq, then formats that file. Make it executable with chmod +x.

See: Auto-format code after edits

Block protected files

settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/protect-files.sh" }
        ]
      }
    ]
  }
}

protect-files.sh

#!/bin/bash
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
  *.env|*/package-lock.json|*/.git/*)
    echo "Protected file: $f" >&2; exit 2 ;;
esac
exit 0

Exit 2 blocks the edit and shows stderr to Claude. Use the permission system for hard allow and deny rules.

See: Block edits to protected files

Notify when needed

{
  "hooks": {
    "Notification": [
      {
        "matcher": "permission_prompt|idle_prompt",
        "hooks": [
          { "type": "command",
            "command": "notify-send 'Claude Code' 'Needs input'" }
        ]
      }
    ]
  }
}

permission_prompt waits about six seconds; idle_prompt about 60 seconds.

See: Get notified when Claude needs input

Add context

settings.json

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/context.sh" }
        ]
      }
    ]
  }
}

context.sh

#!/bin/bash
echo '{"hookSpecificOutput":{
  "hookEventName":"SessionStart",
  "additionalContext":"Run pnpm test before committing"
}}'

Injected context stays under 10,000 characters per field.

See: Add context for Claude

Run in background

{
  "type": "command",
  "command": ".claude/hooks/run-tests.sh",
  "async": true,
  "asyncRewake": true
}

Async hooks don't block the turn; asyncRewake wakes Claude on exit 2 and shows stderr as a system reminder.

See: Run hooks in the background

Events

Session

EventFires when
SessionStartSession begins or resumes
SetupInit-only or maintenance run
PreCompactBefore context compaction
PostCompactAfter compaction
ConfigChangeA settings file changes
SessionEndSession terminates

See: Hook lifecycle

Prompts

EventFires when
UserPromptSubmitPrompt submitted, before processing
UserPromptExpansionA command expands into a prompt
StopClaude finishes responding
StopFailureTurn ends on an API error
NotificationA notification is sent

See: Hook events

Tools

EventFires when
PreToolUseBefore a tool call; can block
PermissionRequestA tool needs a decision
PermissionDeniedAuto mode denies a call
PostToolUseTool call succeeds
PostToolUseFailureTool call fails
PostToolBatchA parallel batch resolves

See: Hook events

Files and agents

EventFires when
FileChangedA watched file changes
CwdChangedThe working directory changes
DirectoryAdded/add-dir adds a directory
InstructionsLoadedCLAUDE.md is loaded
SubagentStartA subagent is spawned
SubagentStopA subagent finishes

See: Hook events

Configuration

Locations

FileScope
~/.claude/settings.jsonAll your projects
.claude/settings.jsonOne project, shareable
.claude/settings.local.jsonOne project, personal
Managed settingsOrganization-wide
Plugin hooks/hooks.jsonWhile plugin is enabled
Skill frontmatterAfter invocation, until /clear
Subagent frontmatterWhile that subagent runs

Hook entries merge across scopes instead of replacing each other.

See: Hook locations

Matchers

ValueMeaning
*, "", or omittedEvery occurrence
BashExact tool name
Edit\|WriteEither tool
^NotebookRegex: name starts with
mcp__memory__.*Regex: server tools

Regex applies when the value contains characters outside letters, digits, _, -, spaces, ,, and |.

See: Matcher patterns

Handler types

TypeRuns
commandShell command; JSON on stdin
httpPOST event JSON to a URL
mcp_toolCall a configured MCP tool
promptSingle-turn model decision
agentSubagent with Read, Grep, Glob

Prompt and agent hooks are capped at 12 concurrent runs.

See: Hook handler fields

Fields

{
  "matcher": "Bash",
  "hooks": [
    {
      "type": "command",
      "if": "Bash(git *)",
      "command": ".claude/hooks/git-check.sh",
      "timeout": 30,
      "statusMessage": "Checking git command"
    }
  ]
}

if filters five tool events; on other events the hook never runs. Commands default to 600s, prompts to 30s, and agents to 60s.

See: Common fields

Disable

CommandEffect
/hooksBrowse loaded hooks
claude --settings '{"disableAllHooks": true}'Disable for one run
claude -p --bare "review this"Skip hooks and plugins

disableAllHooks temporarily disables unmanaged hooks; managed hooks need managed settings. --settings overrides project settings for one run. Delete a hook's entry to remove it.

See: Disable or remove hooks

Decisions

Exit codes

CodeResult
0Success; apply JSON on stdout
2Block when supported; stderr explains
otherNon-blocking error

onFailure: "block" also blocks on hook failure. On events that cannot block, exit 2 is ignored or only surfaces stderr; see exit code behavior per event.

See: Exit code output

JSON output

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Destructive command"
  }
}

Exit 0 and print only JSON for finer control than exit codes.

See: JSON output

Output fields

FieldEffect
decision: "block"Reject a prompt or add feedback
continue: falseStop Claude entirely
systemMessageWarn the user
terminalSequenceEmit an allowed OSC sequence

permissionDecision and additionalContext are per-event; put them in hookSpecificOutput with hookEventName.

See: Decision control

Also see

0 Comments for this cheatsheet. Write yours!