Claude Code hooks: recipes we ran, and the cases where they do not block

Eight Claude Code hook recipes with settings and scripts, each run in a real headless session on version 2.1.314, plus the setups that look safe and are not.

By

A Claude Code hook is a command that runs at a fixed point in a session, so the behavior you want happens every time instead of whenever the model remembers. This page gives eight hook recipes with the settings and scripts, and says what happened when each one ran. It also covers the setups that look like protection and are not.

Who ran the tests. An AI agent procedure ran every test below on 2026-10-30, using Claude Code 2.1.314 with the model claude-sonnet-5-5, on Linux with bash 5.2 and jq 1.7. No person ran them by hand. Each scenario ran once in a fresh temporary project, as a headless session (claude -p, with the output recorded as stream-json including hook events). One run shows what can happen, not how often. Windows and macOS were not tested. The scripts, settings, prompts and raw transcripts are kept in our evidence archive.

The short version

  • Exit code 2 blocks. Exit code 1 does not: the action goes ahead and you only see a notice. We ran both and the file was overwritten on exit 1.
  • A matcher of Edit|Write does not see files written through the Bash tool. echo B=2 > .env went straight through a hook that blocked the Write tool.
  • Block with exit 2 or a JSON deny decision. Both worked on a PreToolUse hook.
  • A PostToolUse hook runs after the tool. It can show Claude a message, but it cannot undo the write.
  • If a hook script is missing or crashes, the default is to let the action through. Set "onFailure": "block" on policy hooks.
  • Hooks are not a substitute for permission rules when you need a guarantee. See the last section.

How a hook is configured

Hooks live in .claude/settings.json (shared with the team), .claude/settings.local.json or your user settings. Each entry names an event, an optional matcher and one or more handlers. The script gets a JSON description of the event on standard input. The hooks reference lists 33 events in its exit-code table; the recipes here use five: PreToolUse, PostToolUse, SessionStart, Stop and Notification.

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

Put scripts in .claude/hooks/, make them executable with chmod +x, and quote $CLAUDE_PROJECT_DIR. Scripts need jq to read the input.

Project hooks need no trust prompt in a headless run. The reference says a -p session never shows the workspace trust dialog and treats the folder as trusted. Our runs agree: the project hooks fired in folders no person had accepted. If you script claude -p over a repository you did not write, read its .claude/ settings first, or start with --bare or --settings '{"disableAllHooks": true}'.

Recipe 1: block edits to protected files

Event PreToolUse, matcher Edit|Write. Exit 2 stops the tool call, and the stderr text goes back to Claude as the reason.

#!/bin/bash
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
  *.env) echo "Blocked: .env files are protected" >&2; exit 2 ;;
esac
exit 0

What we saw. We asked Claude to overwrite .env with the Write tool. The hook exited 2, the tool result was PreToolUse:Write hook error: ... Blocked: .env files are protected, and .env kept its original content. Claude told the user the write was blocked and did not try another route in that run. Run on the script alone, the same input gives exit 2, and a path like src/app.js gives exit 0.

Recipe 2: the same rule with a JSON decision

If you prefer structured output, exit 0 and print a deny decision. Do one or the other: the reference says that when you mix them, exit 2 keeps its blocking effect.

#!/bin/bash
f=$(jq -r '.tool_input.file_path // empty')
case "$f" in
  *.env)
    jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:".env files are protected"}}'
    ;;
esac
exit 0

What we saw. The hook exited 0 with that JSON, the Write was refused with the reason text, and .env was unchanged. It gave the same protection as recipe 1. The advantage is a cleaner reason string and room for ask or allow decisions.

Recipe 3: block risky shell commands

Event PreToolUse, matcher Bash. The script reads tool_input.command.

#!/bin/bash
cmd=$(jq -r '.tool_input.command // empty')
if echo "$cmd" | grep -Eq 'rm -rf|git push (.* )?--force'; then
  echo "Blocked: destructive command" >&2
  exit 2
fi
exit 0

What we saw. Claude was asked to create a directory and delete it with rm -rf. The hook saw the whole compound command, exited 2, and nothing ran. Claude said it would not try to get around the block. Script-level, git push --force origin main is blocked as well.

A gap in our own pattern. The pattern only matches --force. The same script, run directly with git push -f origin main, exits 0 and lets it through. Pattern matching on command text is a filter, not a policy; list every spelling you care about, or use permission deny rules.

Narrowing with if

A handler can carry an if filter so the script only starts for commands you care about: "if": "Bash(git push *)". We tried it two ways:

  • echo hello did not start the hook at all (no hook event in the transcript), and git push --force origin main did start it and was blocked.
  • git -C . push --force origin main did not start the hook. The command was still stopped, but only by the normal permission prompt, which in a headless session with no allow rule is a refusal. In an interactive session with that command allowed, nothing from your hook would have been in the way.

The reference calls the if filter best-effort: when Claude Code cannot tell which commands the input runs, it starts your hook anyway, but a pattern that does not match a variant simply does not start it. Use if to save process spawns, never as the only guard.

Recipe 4: format files after Claude writes them

Event PostToolUse, matcher Edit|Write. This example runs Prettier on files it can format.

#!/bin/bash
f=$(jq -r '.tool_response.filePath // .tool_input.file_path // empty')
case "$f" in
  *.json|*.js|*.ts|*.md|*.css) [ -f "$f" ] && npx --no-install prettier --write "$f" ;;
esac
exit 0

What we saw. Claude wrote data.json as {"b":[1,2,3],"a":{"x":1}} on one line. After the hook ran, the file held { "b": [1, 2, 3], "a": { "x": 1 } }, which is Prettier 3.9.10’s output. Claude noticed that the file may no longer match what it wrote.

What did not work first. Our first attempt used a trailing-whitespace stripper. We asked for lines with trailing spaces, and Claude removed the spaces itself before writing, so the hook had nothing to change and the test proved nothing. We kept that run in the evidence as inconclusive and switched to a formatter whose output Claude would not produce on its own.

Recipe 5: a Stop gate that runs your tests

Event Stop. Exit 2 keeps Claude working and sends it your stderr. Always check stop_hook_active, which is true when Claude is already continuing because of a stop hook.

#!/bin/bash
input=$(cat)
if [ "$(echo "$input" | jq -r .stop_hook_active)" = "true" ]; then exit 0; fi
if ! out=$(cd "$CLAUDE_PROJECT_DIR" && bash ./test.sh 2>&1); then
  echo "Tests are failing, fix them before stopping: $out" >&2
  exit 2
fi
exit 0

What we saw. The project’s test.sh always failed on purpose. With the guard, the hook ran twice: once with stop_hook_active=false (blocked, Claude investigated), once with true (let the session end). Without the guard line, the hook ran ten times, nine of them with stop_hook_active=true, and Claude kept answering that it could not fix a stub test. The session ended anyway, which fits the documented cap: after eight consecutive continuations Claude Code overrides the next block (set CLAUDE_CODE_STOP_HOOK_BLOCK_CAP to change it, and the count resets when Claude calls a tool). The unguarded run cost about 75 percent more than the guarded one in our two samples ($0.125 against $0.071, one run each), so an unguarded gate on a test that cannot pass spends money.

The guard has a price: it lets the second stop through even if the tests still fail. If you need a hard gate, check the tests in CI too. Whether a project needs that gate at all is a budget question; here is how I decide which checks stay.

Recipe 6: log every shell command

Event PostToolUse, matcher Bash. A plain audit trail.

#!/bin/bash
jq -c '{ts: (now|todate), session: .session_id, command: .tool_input.command}' >> "$CLAUDE_PROJECT_DIR/audit.jsonl"
exit 0

What we saw. Two separate Bash calls (echo one, echo two) produced two lines in audit.jsonl, each with the session ID and the exact command. It logs after the command has run. We did not test whether a command refused by a PreToolUse hook appears in such a log, so do not rely on it to record attempts.

Recipe 7: give Claude context at session start

Event SessionStart. Anything the script prints to standard output is added to Claude’s context.

#!/bin/bash
echo "Project rule from hook: the release codename is CANARY-HOOK-7731."

Use a matcher of startup, resume, clear or compact to choose when it runs. The compact value fires after compaction and is the usual place to re-inject rules that compaction may drop.

What we saw. With the startup matcher, we asked for the release codename in a new session. Claude quoted CANARY-HOOK-7731 and said it learned it from the SessionStart hook, not from a file. The compact matcher was not tested: we did not trigger a compaction. Output over 10,000 characters is saved to a file and replaced with a preview, so keep injected context small.

Recipe 8: notify when Claude needs you

Event Notification. The input has message, title and notification_type.

#!/bin/bash
jq -r '"[" + .notification_type + "] " + .message' >> "$CLAUDE_PROJECT_DIR/notify.log"
exit 0

Swap the last line for notify-send on Linux or osascript on macOS to get a desktop alert.

What we tested. Script level only: with the documented sample input the script appended [permission_prompt] Claude needs your permission to use Bash. A headless session does not raise notifications, so no session-level run exists. Notification hooks cannot block anything; the reference says exit code and stderr are ignored for this event.

The cases where a hook does not block

Exit code 1

We ran recipe 1’s script with exit 1 instead of exit 2. The hook ran, printed its message to stderr, and Claude Code recorded a non-blocking error. The Write tool still reported success and .env became B=2. The reference states it plainly: exit 1 without valid JSON is a non-blocking error, even though 1 is the usual Unix failure code. For policy, use 2.

A matcher that names the wrong tool

With the Edit|Write hook from recipe 1 in place, we asked Claude to run echo B=2 > .env through the Bash tool. The hook never started, and .env was overwritten. If a file must not change, protecting the file tools is not enough. Options: add a Bash hook that rejects redirections to that path (leaky, see recipe 3’s gap), or deny the paths in permission rules (not tested here).

A missing or crashing script

We pointed a PreToolUse Bash hook at a script that does not exist. The hook failed with exit 127 and Claude’s ls ran anyway. With "onFailure": "block" on the same hook, the call was blocked and the message read failed; blocking because onFailure is "block".

{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check.sh", "onFailure": "block" }

onFailure needs Claude Code 2.1.295 or later (the changelog dates it October 8, 2026). Without it, a typo in the path means your policy hook silently does nothing, so check for the hook error notice the first time you run it.

After the fact

We made a PostToolUse hook on Write exit 2. The file out.txt was created and stayed there. Claude saw “Lint failed: please fix”, read the hook, and reported that the hook fails on every write. For PostToolUse, exit 2 shows stderr to Claude, but the tool has already run.

When a hook is the wrong tool

The memory documentation describes CLAUDE.md as context, not enforced configuration. A hook is closer to enforcement, but the Bash gap above shows it is still pattern matching on what the model chose to do. When you need a guarantee, such as never reading secrets or never pushing to main, use permission deny rules and keep hooks for reactions and checks. The reference itself says to use the permission system rather than a hook to enforce a hard allow or deny. We did not test deny rules here. For instructions that guide behavior without enforcing it, see CLAUDE.md and AGENTS.md: an annotated example. For a procedure Claude should follow only on some tasks, see Claude Code skills; a skill can also carry its own hooks in its frontmatter.

What we did not test

  • macOS, Windows and PowerShell hooks.
  • The compact matcher, PreCompact, and every event not named above.
  • async, http, prompt and agent hooks, and Stop gates with onFailure.
  • Interactive sessions: the workspace trust dialog and permission prompts behave differently from -p runs.
  • Repeat runs. Each scenario ran once, and the model’s wording will differ on another run.

Keeping this page honest

Hooks changed several times in the weeks before this was written. Every result above is for Claude Code 2.1.314 on 2026-10-30. The recipes should be rerun on each Claude Code minor version we mention; run-all.sh and unit-checks.sh in the evidence folder do that.