Claude Code: exit 1 in Hooks ließ 19 blockierte Befehle trotzdem laufen
Ein Claude-Code-Guard-Hook meldete 19-mal in drei Wochen den blockierten Befehl rm -rf außerhalb des Projekts. Der Abgleich mit den Session-Transkripten zeigte, dass alle 19 Befehle trotzdem ausgeführt wurden: Der Hook beendete sich mit exit 1, was Claude Code nicht als Block interpretiert.

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.
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.
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".
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" } ] } ] } } Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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.
exit 2 Enter fullscreen mode Exit fullscreen mode 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.
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:
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.
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.
#!/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 Enter fullscreen mode Exit fullscreen mode 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 ) Enter fullscreen mode Exit fullscreen mode Two details matter here:
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" } } Enter fullscreen mode Exit fullscreen mode 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.
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.
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) Enter fullscreen mode Exit fullscreen mode 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.
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.