My guard hook printed BLOCKED: rm -rf outside project nineteen times in three weeks. I felt great about it. Then I lined the hook log up against the session transcripts and found that all nineteen commands had run anyway.
The hook did exactly what I told it to. I told it to exit 1. In Claude Code, the hook exit code decides whether a tool call gets blocked, and exit 1 doesn't block anything. It shows an error and lets the call go ahead.
If you've written a PreToolUse hook for Claude Code, check your exit codes before you read anything else.
TL;DR
- In Claude Code, only exit code 2 blocks a PreToolUse tool call. Claude gets your stderr as the reason.
- exit 0 means success. Any other non-zero code (1, 127, a crash) is a non-blocking error: you see stderr, and the tool call goes ahead.
- So a hook that crashes fails open. A missing
jq, a Python traceback or an unset variable underset -uall exit non-zero but not 2, and the command runs. - The fix: block with
exit 2, and turn every unexpected failure intoexit 2with atrap(bash) or a top-leveltry/except(Python). - JSON decisions (
permissionDecision: "deny") are only read when the hook exits 0.
What do Claude Code hook exit codes actually mean?
Claude Code hook exit codes have three meanings: 0 is success, 2 is a blocking error, and everything else is a non-blocking error. For a PreToolUse hook, "blocking" means the tool call is cancelled and your stderr goes back to Claude so it can change course. "Non-blocking" means your stderr is shown to you and the tool call goes ahead.
| Exit code | Meaning | PreToolUse effect |
|---|---|---|
| 0 | Success | Tool runs (stdout JSON is parsed, if any) |
| 2 | Blocking error | Tool call cancelled, stderr sent to Claude |
| 1, 3, 127, anything else | Non-blocking error | stderr shown to you, tool runs |
Most of us learned from Unix habit that non-zero means "no". Claude Code treats 2 as the only "no". Every other non-zero code is treated as "something went wrong with the hook", which is a different thing from "deny this call".
What did my broken hook look like?
Here's roughly the hook I ran for three weeks. It's registered in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": ".claude/hooks/guard.sh" }
]
}
]
}
}
And the script:
#!/usr/bin/env bash
set -euo pipefail
cmd=$(jq -r '.tool_input.command')
if [[ "$cmd" =~ rm[[:space:]]+-rf[[:space:]]+(/|~|\.\.) ]]; then
echo "BLOCKED: rm -rf outside project" | tee -a ~/.claude/guard.log >&2
exit 1
fi
exit 0
It looks fine. It matched the right commands, it logged, and the red error text appeared in my terminal every time. That red text is exactly why I never questioned it. A visible error feels like a refusal, but the command still ran.
The fix for this part is one character:
exit 2
After that change, Claude got BLOCKED: rm -rf outside project as feedback, said something like "I'll scope the delete to the build directory instead", and rewrote the command. That's the loop I thought I'd had all along.
Why does a crashing Claude Code hook fail open?
A crashing hook fails open because a crash exits with a code that isn't 2. Bash gives 127 for "command not found" and 1 for most failures, and Python gives 1 for an uncaught exception. Claude Code reads all of those as non-blocking errors and runs the tool.
This one scared me more than the exit 1 mistake, because even after the fix, my hook still had three ways to fail open:
-
jq missing. On a fresh machine without
jq, the very first line dies with exit 127. Nothing gets checked and every command runs. -
set -uon an unexpected payload. If a field I reference isn't there, the script dies with exit 1 before it reaches the check. - A typo in the regex. Bash prints a syntax error, exits with 2 or 1 depending on where it fails, and I can't rely on either.
The point is that any guard you depend on for safety has to treat its own failure as a deny. Claude Code won't do that for you. The default is "a broken hook doesn't break your session", which is the right default for formatters and loggers and the wrong one for safety checks.
How do you make a Claude Code hook fail closed?
You make a Claude Code hook fail closed by catching every unexpected error and converting it to exit 2 with a clear message on stderr. In bash, use an ERR trap. In Python, wrap everything in try/except.
The bash version:
#!/usr/bin/env bash
set -euo pipefail
trap 'echo "guard.sh crashed on line $LINENO; refusing to allow this call" >&2; exit 2' ERR
command -v jq >/dev/null || { echo "guard.sh: jq not installed; blocking" >&2; exit 2; }
cmd=$(jq -r '.tool_input.command // empty')
if [[ "$cmd" =~ rm[[:space:]]+-rf[[:space:]]+(/|~|\.\.) ]]; then
echo "Blocked: rm -rf outside the project. Delete a path inside the repo instead." >&2
exit 2
fi
exit 0
And the Python version, which I now prefer for anything with more than one rule:
#!/usr/bin/env python3
import json, re, sys
def main() -> int:
payload = json.load(sys.stdin)
cmd = payload.get("tool_input", {}).get("command", "")
if re.search(r"rm\s+-rf\s+(/|~|\.\.)", cmd):
print("Blocked: rm -rf outside the project.", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as e:
print(f"guard hook crashed ({e!r}); blocking to be safe", file=sys.stderr)
sys.exit(2)
Two details matter here:
- Write the stderr message for Claude, not for yourself. On exit 2 it becomes Claude's feedback. "Blocked: use a path inside the repo" gets a better retry than "DENIED".
- Fail closed only for guards. Your auto-formatter hook should keep failing open. If Prettier crashes, you don't want every edit refused.
Can a Claude Code hook block with JSON instead of exit 2?
Yes. A PreToolUse hook can print a JSON decision to stdout, but only if it exits 0. If the hook exits 2, the JSON is ignored and stderr is used instead. If it exits 1, nothing is enforced.
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "rm -rf outside the project is not allowed"
}
}
permissionDecision also accepts "allow" (skip the permission prompt) and "ask" (force the prompt). That's useful when you want more than a yes/no answer.
The trap here is the mirror image of the first bug. I've seen hooks that print a perfect "deny" JSON and then exit 1 because "it's an error case". The JSON is never parsed and the command runs. Pick one channel: either exit 2 plus stderr, or exit 0 plus JSON. Don't mix them.
Does exit 2 block in every hook event?
No. Exit 2 means different things depending on when the hook runs. In PreToolUse it cancels the tool call. In PostToolUse the tool has already run, so exit 2 can only send your stderr back to Claude as feedback. It doesn't undo anything.
That catches people who move a guard from Pre to Post "to see the result first". If the check is "don't run this", it has to be a PreToolUse hook. A PostToolUse exit 2 is for "that edit broke the linter, go fix it", which is a great use of it, just not a safety boundary.
How do I test that my hook really blocks?
Pipe a fake payload into it and check the exit code yourself, before trusting it in a session:
echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf ~/"}}' \
| .claude/hooks/guard.sh; echo "exit=$?"
# want: exit=2
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' \
| .claude/hooks/guard.sh; echo "exit=$?"
# want: exit=0
echo 'not json' | .claude/hooks/guard.sh; echo "exit=$?"
# want: exit=2 (this is the fail-closed test)
That third test is the one I'd skipped. Malformed input is the cheapest way to find out whether your guard fails open.
Then do one live check: ask Claude to run something your hook should refuse, and confirm it rewrites the command instead of running it. If you see your error text and then normal output, the hook isn't blocking.
So does exit 1 block a Claude Code hook?
No. In Claude Code, exit 1 from a hook is a non-blocking error: your stderr is shown and the tool call still runs. Only exit code 2 blocks a PreToolUse call and sends stderr back to Claude, and JSON permissionDecision: "deny" is only honored when the hook exits 0. Because crashes, missing binaries and uncaught exceptions also exit with something other than 2, a guard hook fails open unless you trap every unexpected error and convert it to exit 2. Use exit 2 for guards, test them with malformed input, and let your formatter hooks keep failing open.
Written by the developer behind Preterview, an interview prep platform.
Top comments (4)
Only exit 2 blocking is how I read the docs too, so the fail-closed trap is the right fix. One more layer your pipe tests don't cover is how the hook gets started. On Windows a shell-form entry like .claude/hooks/guard.sh goes through Git Bash (PowerShell if Git for Windows is missing), so a shell with its own quoting sits between Claude and your script. Since Claude Code 2.1.139 there is an exec form, command plus an args array, that starts the program without any shell. On my laptop under load the median per hook was 31 ms exec, 51 ms cmd, 81 ms Git Bash and 324 ms PowerShell, which adds up because PreToolUse and PostToolUse run on every tool call. Do you run your guards on Windows as well, or only macOS and Linux?
The fail-open point is the sharpest part: since only exit 2 blocks, a missing jq (127) or a set -u crash quietly lets the command through, so the ERR trap that turns any crash into exit 2 is worth copying into every safety hook. One more guard I'd add is a startup self-test that feeds the hook a known-bad payload and asserts it returns 2, so a broken environment gets caught before a real command slips past.
The fail-open crash case is the one that stays invisible, because the red error text looks like a refusal. A cheap regression test is a few fixture runs of the hook: a command it should block, a command it should allow, empty stdin, malformed JSON, and a PATH without jq. Assert the exit code each time (2 for block, 0 for allow, and 2 for the broken-input cases if you want it to fail closed). It also helps to log the exit code next to BLOCKED so the log line and the actual behavior can't drift apart like they did here.
Nineteen "BLOCKED" lines in three weeks and all nineteen ran is a lock that clicks and doesn't latch. Lining the hook log up against the transcripts is the step that found it, and it's the one most people skip because the log already says what they want to hear. Coming from carpentry, a guard that fails open is worse than no guard, because people stop being careful around it. On a saw, the brake is supposed to be what happens when something breaks. Exit 2 blocks and everything else lets it through is worth a comment at the top of every hook file. I direct agents as a Language Modeler, and I'd test a new hook the way you found this one: have it block something harmless and check that the thing didn't run.