Skip to content

Claude

Claude Code Hooks: Exit 2 vs JSON Deny on a Real rm -rf

We told Claude Code to run rm -rf and tested hooks against it: a PreToolUse hook that exits 2 and one that returns a JSON deny both kept the folder, at about one extra turn. Examples, the full event list and hooks vs skills.

By Duy Lam Le, written with AI8 min read

Why trust this: every result, number and screenshot comes from a real run on our own accounts, not from the AI. How we test

Đọc bản tiếng Việt →

Screenshot: table of four Claude Code hooks test runs, two PreToolUse hooks blocking rm -rf and keeping the folder
Screenshot from the test run.

Claude Code hooks are scripts Claude Code runs on its own at fixed points, such as right before a tool call. We told Claude to delete a folder with rm -rf and ran it four ways: no hook, a hook that exits with code 2, a hook that returns a JSON "deny", and a logging hook. Both blocking hooks saved the folder. Without a hook, it was gone.

At a glance

Key results

  • Both blocking hooks worked, 2 out of 2. The PreToolUse hook that exits 2 and the one that prints permissionDecision: "deny" each stopped the rm -rf call, and the scratch/ folder survived. Without a hook, Claude deleted it as asked.
  • Claude did not look for a way around the block. In both blocked runs it reported that the folder was still there, quoted the hook as the reason and said it had not tried another method.
  • A block costs about one extra turn. Blocked runs took 3 turns, 6.6 to 7.2 seconds and 0.044 to 0.045 USD on Sonnet. The run without a hook took 2 turns, 4.1 seconds and 0.039 USD.
  • The hook checks whole commands, not single words. Claude chained rm -rf scratch; ls into one Bash call, so the hook blocked the ls too. Claude then ran ls alone, and the hook let it through.
  • A PostToolUse hook fired once for a two-step task. Asked to create a file and count its lines, Claude did both in one Bash call, so a hook matched on every tool (*) ran once, not twice.
  • What a hook receives: 10 JSON fields on stdin for PreToolUse, 12 for PostToolUse (adds tool_response and duration_ms).
Table of the four Claude Code hooks test runs: hook type, hook calls, blocked calls, whether the scratch folder survived, turns, seconds and cost in USD
Real output of our 17 Nov 2026 run on Claude Code 2.1.325 with Sonnet: counts come from the hook's own log file

Hands-on test

Setup

  • Claude Code: version 2.1.325, model Sonnet, run headless with claude -p on a laptop signed in to a paid Claude plan, 17 November 2026. Costs below are the total_cost_usd that claude -p reports.
  • Isolation: every case ran in a fresh temporary folder holding a scratch/ folder with three placeholder files. We passed the hook with --settings <file> and --setting-sources local, so no user or project hooks from the machine could mix in.
  • Permissions: --allowedTools Bash Write Read and --permission-mode acceptEdits, so a blocked call could only come from the hook.
  • Hooks: short Python scripts. Each one appended the JSON it received to hook-log.jsonl before deciding, so the counts below come from the hook, not from Claude's answer.
  • Docs: the official hooks reference and hooks guide, read on 17 November 2026.

Claude Code hooks explained

Anthropic's guide describes hooks as user-defined commands that give "deterministic control: certain actions always happen rather than relying on the LLM to choose to run them". In practice, a hook has three parts in a settings file:

  1. An event, such as PreToolUse (before a tool runs) or Stop (when Claude finishes answering).
  2. A matcher that filters the event, such as Bash for shell commands only, or * for every tool.
  3. A handler that runs when both match. Most hooks are shell commands. The reference also lists HTTP endpoints, MCP tool calls, LLM prompts and subagents as handler types.

The handler gets the event as JSON (on stdin for a command hook) and answers with an exit code, JSON on stdout, or both.

You can put hooks in ~/.claude/settings.json (all your projects), .claude/settings.json (one project, can be committed), .claude/settings.local.json (one project, not shared), managed policy settings, a plugin, or the frontmatter of a skill or subagent.

Claude Code hooks examples: what we ran

Example 1: block rm -rf with exit code 2

This is the settings block for the exit2 case. Only the script path is shortened.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "python3 .claude/hooks/block_rm.py" }]
      }
    ]
  }
}

And the script, minus the logging lines:

import json, sys

data = json.load(sys.stdin)
cmd = (data.get("tool_input") or {}).get("command", "")
if "rm -rf" in cmd:
    print("Blocked by PreToolUse hook: rm -rf is not allowed in this project.", file=sys.stderr)
    sys.exit(2)
sys.exit(0)

Exit code 2 means "blocking error". Claude Code stops the tool call and passes your stderr to Claude as the reason. Claude's final answer in our run: "No, scratch is still there: a PreToolUse hook in this project (hook.py) blocks rm -rf, so the command never ran, and I haven't tried another way to delete it."

Example 2: block it with a JSON permission decision

Same matcher and same check, but the script exits 0 and prints this:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "rm -rf is not allowed in this project."
  }
}

The result was the same: one call blocked, scratch/ kept, 3 turns. Claude quoted the reason string word for word in its answer.

Example 3: log every tool call with PostToolUse

A PostToolUse hook with matcher * that only writes the input to a log file and exits 0. It never blocks anything. We asked Claude to create notes.txt with three lines and count them. It wrote one Bash command, printf 'alpha\nbeta\ngamma\n' > notes.txt && wc -l notes.txt, so the hook fired once and logged the result. If you count tool calls with a hook, expect the count to follow how Claude groups its commands, not how many steps you asked for.

The hook's own log: two blocked rm -rf calls, two allowed ls calls, one PostToolUse log line, and the JSON keys each hook received
Every line here was written by the hook script itself during our 17 Nov 2026 run

Exit code 2 vs JSON deny: which to use

Both stopped the call in our test, at the same cost. The difference is what else you can say:

  • Exit 2 is the shortest path. Write the reason to stderr and exit. Use it for a hard "never".
  • JSON on exit 0 gives you more choices than "deny": the reference lists allow, deny, ask and defer for PreToolUse. Use it when the hook should sometimes hand the call to the normal permission prompt instead of refusing.
  • Do not exit 1 to block. The reference treats any exit code other than 0 or 2 as a non-blocking error: "The action goes ahead".
  • Do not mix them. With exit 2, the call stays blocked "even if you return "allow"" in the JSON.

Claude Code hooks lifecycle

The reference sorts events by how often they fire:

  • Once per session: SessionStart and SessionEnd.
  • Once per turn: UserPromptSubmit, Stop and StopFailure.
  • On every tool call: PreToolUse and PostToolUse.

Around those sit events for permissions, subagents, tasks, compaction, worktrees, file changes, model switches and MCP elicitation. Our runs touched two of them. The tool-call events are where most project rules belong, because they see the exact command before or after it runs.

Claude Code hooks list

The events table in the hooks reference had 33 entries when we read it on 17 November 2026:

WhenEvents
SessionSetup, SessionStart, SessionEnd, InstructionsLoaded, ConfigChange
Prompt and turnUserPromptSubmit, UserPromptExpansion, Stop, StopFailure, MessageDisplay, Notification
Tool callsPreToolUse, PermissionRequest, PermissionDenied, PostToolUse, PostToolUseFailure, PostToolBatch
Subagents and tasksSubagentStart, SubagentStop, TaskCreated, TaskCompleted, TeammateIdle
Context and modelPreCompact, PostCompact, PreModelSwitch, PostModelSwitch
Files and foldersCwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove
MCPElicitation, ElicitationResult

The grouping is ours. The reference also says which events can block and what exit code 2 does on each one.

What a hook receives on stdin

Our PreToolUse hook got 10 keys: cwd, effort, hook_event_name, permission_mode, prompt_id, session_id, tool_input, tool_name, tool_use_id and transcript_path. The PostToolUse hook got the same plus tool_response and duration_ms. The reference documents one more common field, scratchpad_dir, which is absent when the session has no scratchpad. Our headless runs did not receive it, so check for it before you use it.

Claude Code hooks vs skills

They solve different problems, and our runs show why:

  • A skill is instructions. Anthropic's skills page says you "create a SKILL.md file with instructions" and "Claude uses skills when relevant". Claude decides when to read it and how to follow it. Use a skill to teach a workflow, such as how to review a diff. Our guide to creating a Claude skill shows a full example.
  • A hook is a rule the program enforces. Claude Code runs it on every matching event whether Claude agrees or not. In our test Claude was told to run rm -rf, and the hook still stopped it.

They combine well. A skill can declare its own hooks in its frontmatter. They start only when the skill is invoked and stay registered until you exit or leave the conversation with /clear or /resume.

What worked

What worked

  • Logging from inside the hook. The counts and the exact commands came from the hook's own file, so we did not have to trust Claude's summary.
  • Testing with --setting-sources local in a throwaway folder. No hook from the machine could change the result.
  • Both blocking styles. Claude respected the block and explained it without being told to.

Where it fell short

What didn't work

  • Matching on the text rm -rf is crude. It also blocked the harmless ls in the same call, and it would miss rm -r -f or a script that deletes files. For real projects, match on the parsed command or allow a short list of safe commands instead.
  • We tested headless runs only (claude -p). We did not test the interactive /hooks menu or HTTP, prompt or agent handlers.
  • One run per case. Timing and cost will vary between runs; the yes or no results matched what the reference describes.

Our verdict

Use a PreToolUse hook for anything that must never happen, and do not rely on CLAUDE.md or a skill for it. Start with exit code 2 and a clear stderr message: it is the simplest form and it held in our test. Switch to JSON when you need ask or allow. Expect about one extra turn each time a hook blocks, and match on whole commands, because Claude often chains several steps into one Bash call. For how hooks and other features affect your usage, see our Claude Code usage limits breakdown. To split work across agents, see our fork subagents test.

FAQ

Where is the Claude Code hooks documentation?

Anthropic keeps two pages: the hooks guide with step-by-step examples and the hooks reference with every event, input field and exit code. This page adds a measured run on top of them.

Do Claude Code hooks run in headless mode?

Yes. All four of our runs used claude -p, and both blocking hooks fired.

Does a hook slow Claude Code down?

We did not time the hook scripts on their own. The blocked runs took 2.5 to 3.1 seconds longer than the run without a hook, and each had one more turn, in which Claude reacted to the block.

Claude, the AI assistant, wrote the test script, ran the four cases and wrote this page. Results come from the hook log and the JSON output of claude -p; every Claude Code claim was checked against the Anthropic documentation linked above.

Claude

Claude Fable 5.2 vs Opus 5.5: Perfect Score at 2.6x the Cost

We re-ran three sealed office tests (a trap-filled spreadsheet, a long contract and a month-end close with tools) on Claude Fable 5.2, Opus 5.5 and Sonnet 5.5 through the API. Fable 5.2 scored 10/10 in all 18 runs; it cost 2.6 times Opus 5.5 at default effort and 1.7 times at medium.

Claude

Claude Code Don't Ask Again: Where Your Password Goes

We clicked "Yes, and don't ask again" on a Claude Code command with a fake password. The password landed in .claude/settings.local.json in plain text, the only thing keeping it out of git was a global ignore rule, and on a fresh machine Claude committed the file itself.

Latest guides

All guides