Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Cheat sheet

Claude Code hooks cheat sheet

PreToolUse and PostToolUse events, matcher patterns, stdin JSON payload fields, exit codes and safe config examples.

By Checked Intermediate
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

Claude Code hooks run deterministic shell commands around lifecycle events such as tool execution, so formatting, logging and destructive-command blocks never rely on the model remembering an instruction. Put project hooks in .claude/settings.json and exit with code 2 from PreToolUse to block a call. See Claude Code hooks for a full walkthrough.

Minimal .claude/settings.json template

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous-bash.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-changed-file.sh"
          }
        ]
      }
    ]
  }
}

Core tool events

Event When it fires Can block tool call? Typical use
PreToolUse Before a matched tool runs Yes (exit 2 or JSON decision) Block rm -rf, force-push, edits to migrations/
PostToolUse After a matched tool succeeds No (already ran) Run Prettier/Ruff, append audit logs, run fast checks

Matcher patterns

Pattern Matches Example use
"Bash" Exact tool name Bash Inspect shell commands before execution
"Write|Edit" Alternation matching either tool Auto-format edited files after write
"^Notebook" Regex prefix match Guard notebook edits
"mcp__.*" All tools from connected MCP servers Log or restrict external MCP calls
"mcp__memory__.*" Every tool from the memory server (a bare mcp__memory matches nothing) Guard one server
"REPL" The tool that runs Claude’s JavaScript in Code Mode Read or redact the code and its output
"*", "" or omitted Every tool call Global audit logging

A matcher made only of letters, digits, _, -, spaces, , and | is compared as exact names, so Edit|Write matches those two tools only. Any other character makes it an unanchored regular expression: Edit.* also matches NotebookEdit, so use ^Edit$ for one tool.

Exit codes and stdout contract

Exit code Meaning What Claude Code reads
0 Pass / allow (normal permission flow continues) Optional structured JSON on stdout for custom decisions
2 Block / veto action (PreToolUse) Text printed to stderr is shown to Claude as the denial reason
1 (other non-zero) Script execution error Treated as a hook error rather than a policy block

To make a crashed or timed-out guard block instead of letting the call through, set "onFailure": "block" on the command or http hook (Claude Code v2.1.295 or later). "continue" and leaving it unset both let the action go ahead.

Common stdin JSON fields

Claude Code passes event context as JSON on stdin. Read it with jq or Node/Python rather than shell string matching:

# Inspect tool_name and Bash command inside a PreToolUse hook
payload="$(cat)"
tool="$(printf '%s' "$payload" | jq -r '.tool_name // ""')"
cmd="$(printf '%s' "$payload" | jq -r '.tool_input.command // ""')"
Field Example value Notes
hook_event_name "PreToolUse" Event that triggered the hook
tool_name "Bash", "Edit", "Write" Tool invoked by Claude
tool_input {"command": "git status"} Tool parameters; shape depends on tool_name
session_id Session identifier string Useful for correlating audit logs

Hook configuration scopes

Choose the settings file based on who should inherit the hook and whether it belongs in version control:

File path Scope Committed to Git? Best for
.claude/settings.json Current repository (team-wide) Yes Shared formatters, repo safety blocks, migration guards
.claude/settings.local.json Current repository (your machine only) No (gitignored) Personal notifications, local tool paths, WIP hooks
~/.claude/settings.json All repositories for your user No Global destructive-command guards and audit logs

Hooks in Code Mode (experimental)

In Code Mode (CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1, v2.1.323 or later), Claude writes JavaScript that makes several tool calls in one step, and a tool called REPL runs it. Hooks still see each call:

What you want Hook Notes
Check each tool call the code makes PreToolUse on the usual name, such as Bash or an MCP tool Same as without Code Mode; check every part of a compound command, as cd 'app' && git push can reach the hook
Check the code before it runs PreToolUse matching REPL Read the JavaScript from tool_input.code
Check or redact what the code returns PostToolUse matching REPL Read tool_response (code, result, stdout, stderr, toolsUsed); return a redacted copy as updatedToolOutput
Stop a call when its guard hook fails "onFailure": "block" on a command or http hook Unset, a timed-out PreToolUse hook refuses the call, but one that fails another way passes the call on to the normal permission checks

Keep the shape of tool_response when you redact (code, stdout and stderr as strings), or Claude gets the original output. From v2.1.328, UserPromptSubmit hooks no longer receive code output, so move output checks to PostToolUse on REPL. Code Mode can change or be removed in any release; see the Code Mode docs before relying on it.

Common mistakes

Mistake Fix
Exiting with 1 to block a command Use exit 2 and print the reason to stderr
Trying to block inside PostToolUse Move blocking checks to PreToolUse
Running slow full-repo tests on every Edit Format or lint only the single edited file path from tool_input
Hard-coding /Users/name/... paths in shared .claude/settings.json Reference "$CLAUDE_PROJECT_DIR" and commit scripts under .claude/hooks/
Forgetting chmod +x on hook scripts Make every hook script executable and test it with piped sample JSON

Test a hook from the terminal

printf '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git push --force"}}' \
  | .claude/hooks/block-dangerous-bash.sh
echo "exit=$?"

Confirm exit 2 on blocked inputs and exit 0 on safe commands before relying on the hook. For ready-made guardrail recipes, see Set up guardrail hooks for coding agents and Permissions and sandboxing for coding agents. For slash commands, flags and permission modes, see the Claude Code cheat sheet.

Check your understanding

Claude Code hooks reference quiz

PreToolUse and PostToolUse, matcher patterns, exit codes, reading stdin JSON, settings file scopes and testing a hook from the terminal.

7 questions · pass mark 70%

Question 1 of 70 answered
  1. You want to stop Claude Code running git push --force. Which event does the hook belong on?

Checked against

  • Claude Code hooks: run checks around every tool call

    Write Claude Code PreToolUse and PostToolUse hooks that block destructive shell commands, format every file Claude edits and log each command for later audit.

    TutorialIntermediate40 min

  • Set up guardrail hooks for your coding agent

    Block dangerous commands in Claude Code with PreToolUse hooks and deny rules, so the agent cannot force-push, wipe files or edit secrets. Test them first.

    WorkflowIntermediate1 h6 steps

  • Permissions and sandboxing for coding agents

    Set up Claude Code permission modes and rules, the Codex sandbox and approvals, and a dev container, so an agent can work without free rein.

    TutorialIntermediate45 min

  • Git guardrails for Claude Code

    Matt Pocock's skill that sets up a Claude Code hook to block destructive Git commands such as push, reset --hard, clean and branch -D before they run.

    Agent Skill

  • Claude Code cheat sheet

    Claude Code slash commands, CLI flags, headless -p runs, permission modes including auto, keyboard shortcuts and config files, checked against Anthropic's docs.

    Cheat sheetIntermediate

Back to top