HOW-TO GUIDE
How to make a Claude Code hook actually block a command with exit 2
Based on a guide by jidonglab on DEV Community · Nov 29, 2026
You'll end with: A PreToolUse guard hook that blocks with exit 2, sends its reason to Claude, and fails closed when it crashes.
Why it's worth having: Exit 1 is a non-blocking error in Claude Code, so the author's hook logged BLOCKED 19 times in three weeks while all 19 commands ran.
At a glance
WHO IT'S FOR
IT and OT engineers and developers who rely on Claude Code hooks as safety guards.
LEVEL
Intermediate
COST
Free. The hooks are bash or Python scripts that run in Claude Code.
YOU NEED
Claude Code · A PreToolUse hook in .claude/settings.json · bash or Python · jq
The method, in short
- 1Exit 2 to block a PreToolUse call and write the reason to stderr for Claude; any other non-zero code lets the command run.
- 2Turn every crash into exit 2 with an ERR trap in bash or a top-level try and except in Python, and block when jq is missing.
- 3Use one channel: exit 2 with stderr, or exit 0 with a JSON permissionDecision of deny, since the JSON is ignored on other exits.
- 4Pipe a blocked command, a safe command, and malformed input into the hook, and expect exit 2, 0, and 2.
Read the full guide from jidonglab on DEV Community
The post has the exit code table, the fixed bash and Python hooks, and the three test commands.
Credit: jidonglab on DEV Community