Catalog My learning Blog
Search courses and lessons
Cheat sheet

Claude Code Hooks Cheat Sheet

Hooks run your code at fixed points in Claude Code's loop, so a rule is enforced every time instead of hoping the model remembers it. This page has the events, exit codes and JSON fields you need.

By Naveed Karimi · Checked November 7, 2026 · Print-friendly

Where hooks live and what they look like

FileApplies toCommit it?
~/.claude/settings.jsonAll your projectsNo
.claude/settings.jsonThis projectYes
.claude/settings.local.jsonThis project, just youNo (gitignored)

Hooks also come from plugins (hooks/hooks.json), skill and subagent frontmatter, and managed policy settings. Three levels of nesting: event, then a matcher group, then one or more handlers.

JSON
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-bash.sh" }
        ]
      }
    ]
  }
}
Handler typeRuns
commandA shell command; gets the event JSON on stdin (default timeout 600 s)
httpPOSTs the event JSON to a url
mcp_toolCalls a tool on a configured MCP server
promptAsks a model to decide, with $ARGUMENTS as the event JSON (30 s)
agentRuns an agent to decide (experimental, 60 s)

Matchers: "*", "" or no matcher match everything. Edit|Write matches either tool exactly. Anything with other characters is a regex, such as mcp__github__.* for every tool from the github MCP server. The if field narrows tool events further with permission rule syntax, such as "if": "Bash(rm *)".

The events you'll use most

EventFiresMatcherExit 2
PreToolUseBefore a tool callTool nameBlocks the call
PostToolUseAfter a tool call succeedsTool nameShows stderr to Claude (tool already ran)
PostToolUseFailureAfter a tool call failsTool nameShows stderr to Claude
PermissionRequestWhen a call needs a permission decisionTool nameNot honored; decide with JSON
UserPromptSubmitWhen you send a promptnoneBlocks the prompt
StopWhen Claude finishes respondingnoneKeeps Claude working
SubagentStopWhen a subagent finishesAgent typeKeeps the subagent working
SessionStartSession begins or resumesstartup, resume, clear, compact, forkStderr shown to you only
SessionEndSession endsEnd reasonStderr shown to you only
NotificationClaude Code sends a notificationpermission_prompt, idle_prompt, ...Ignored
PreCompact / PostCompactAround context compactionmanual, autoPreCompact: blocks compaction
ConfigChangeA settings file changes mid-sessionSettings sourceBlocks the change
FileChangedA watched file changes on diskFile namesStderr shown to you only
ElicitationAn MCP server asks you for inputServer nameDeclines the request

There are more (33 in total in November 2026), including SubagentStart, TaskCreated, TaskCompleted, PostToolBatch, CwdChanged, WorktreeCreate and InstructionsLoaded. Run /hooks to see what you have configured.

Exit codes

Exit codeMeaning
0Success. JSON printed to stdout is applied; Claude never sees stderr
2Blocking error. On events that can block, the action stops and your stderr is the reason Claude sees
Anything elseNon-blocking error. The action goes ahead (even exit 1)

To enforce a policy, use exit 2, not exit 1. Exit 2 blocks even if your JSON says allow.

JSON output

FieldWhereEffect
continue: false + stopReasonAny eventStops Claude entirely and shows the reason
systemMessageAny eventWarning shown to you
decision: "block" + reasonUserPromptSubmit, PostToolUse, Stop, SubagentStop, PreCompact, ...Blocks, with the reason fed back
hookSpecificOutput.permissionDecisionPreToolUseallow, deny, ask or defer (deny wins over defer, ask, allow)
hookSpecificOutput.updatedInputPreToolUseRewrites the tool input before it runs
hookSpecificOutput.additionalContextPreToolUse, PostToolUse, SessionStart, ...Adds text to Claude's context
hookSpecificOutput.decision.behaviorPermissionRequestallow or deny
JSON
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}

Input on stdin always includes session_id, transcript_path, cwd, permission_mode and hook_event_name; tool events add tool_name and tool_input. Useful variables: $CLAUDE_PROJECT_DIR (project root) and, in plugins, $CLAUDE_PLUGIN_ROOT.

Example: block rm -rf before it runs

Save as .claude/hooks/check-bash.sh, make it executable with chmod +x, and register it with the settings above. It needs jq and bash.

BASH
#!/usr/bin/env bash
# PreToolUse hook for Bash: refuse rm with both a recursive and a force flag.
cmd=$(jq -r '.tool_input.command // ""')
while IFS= read -r part; do
  set -f; set -- $part; set +f            # split this command into words
  [ "$1" = sudo ] && shift
  [ "$1" = rm ] || continue
  r=0; f=0
  for w in "$@"; do
    case "$w" in
      --recursive) r=1 ;;
      --force) f=1 ;;
      --*) ;;
      -*) case "$w" in *[rR]*) r=1 ;; esac
          case "$w" in *f*) f=1 ;; esac ;;
    esac
  done
  if [ "$r" = 1 ] && [ "$f" = 1 ]; then
    echo "Blocked: rm with recursive and force flags. Delete specific paths instead." >&2
    exit 2
  fi
done < <(printf '%s
' "$cmd" | tr ';&|' '


')
exit 0

It catches rm -rf, rm -Rf, rm -r -f and --recursive --force, including after sudo or &&, and lets rm file.txt and git rm -rf --cached through. It is a guardrail against mistakes, not a security boundary: a determined command can delete files other ways.

For a full walkthrough see the Claude Code hooks tutorial, and the Claude Code cheat sheet for commands and shortcuts.