You block a dangerous Bash command in Claude Code by registering a PreToolUse hook that matches the Bash tool, reads tool_input.command from the JSON Claude Code sends it, and returns a deny decision before the shell ever runs. The hook is a small script plus a few lines in a settings file — no change to Claude Code itself. This walkthrough builds one from a working example and lists the mistakes that quietly let a command through.
What a PreToolUse hook actually receives
A PreToolUse hook fires immediately before Claude Code executes a tool call, for every tool except EndConversation, and it receives a JSON object on stdin. Alongside session metadata (session_id, cwd, permission_mode), a Bash call carries three fields that matter here: tool_name (the string "Bash"), tool_use_id, and tool_input, which contains the full command string Claude is about to run plus its description, timeout, and run_in_background flag. Nothing is redacted or rewritten before the hook sees it, so the script below can match on the exact text that would reach the shell.
{
"session_id": "abc123",
"cwd": "/home/user/my-project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "rm -rf build/",
"description": "Clean build output",
"timeout": 120000,
"run_in_background": false
},
"tool_use_id": "toolu_01ABC123..."
}
Step 1: write the script that makes the call
The hook is just an executable that reads that JSON from stdin, inspects tool_input.command, and tells Claude Code whether to proceed. A minimal version that blocks the one pattern most teams want blocked first — a recursive, forced delete — looks like this:
#!/bin/bash
COMMAND=$(jq -r '.tool_input.command')
if echo "$COMMAND" | grep -q 'rm -rf'; then
jq -n '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Destructive command blocked by hook"
}
}'
else
exit 0
fi
Save it as .claude/hooks/block-rm.sh and run chmod +x .claude/hooks/block-rm.sh. That last step is easy to skip and is the first item in the mistakes table below, because a non-executable script does not fail the way you would expect. Extend the grep pattern (or replace it with a small case statement) to also catch a forced push to a protected branch, a pipe from curl straight into sh, or a write to a raw block device — whatever your team has actually been burned by.
Step 2: tell Claude Code when to run it (the matcher)
Hooks are registered in ~/.claude/settings.json for every project, .claude/settings.json for a shareable project config, or .claude/settings.local.json for a local-only override. Each entry pairs a matcher, which filters by tool name, with one or more handlers to run when it matches.
| Matcher value | Behavior |
|---|---|
"*", "", or omitted | Matches every tool |
Bash | Exact match, Bash tool only |
Edit|Write or Edit, Write | Exact match on either named tool |
mcp__memory__.* | Treated as a regex (it contains a character outside letters, digits, _, -, spaces, , and |), matching every tool from the memory MCP server |
For finer filtering than the tool name, a handler can add an if field using permission-rule syntax, such as "Bash(rm *)". The if field is only evaluated on tool events, and the handler only runs when both the matcher and the if condition match — a detail that is easy to miss when a hook seems to silently never fire.
A complete registration that runs the script above only for Bash calls matching rm *:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
"args": [],
"timeout": 30
}
]
}
]
}
}
${CLAUDE_PROJECT_DIR} expands to the project root, so the same settings file works regardless of where the repository is checked out. The timeout is in seconds and matters more than it looks — see the warning in Step 3.
Step 3: pick exit code or JSON output, not a mix of both
A command hook can respond in two ways, and mixing them is the second common mistake. The exit code always wins.
| Exit code | Effect |
|---|---|
0 | Success. If stdout is a JSON object, Claude Code reads its fields; plain stdout only goes to the debug log. |
2 | Blocks the tool call. Stderr becomes the reason shown to the user. This blocks even if the JSON output said "allow". |
| Any other value | Treated as a non-blocking error. The tool call proceeds, and the transcript shows a hook-error notice — it does not stop anything. |
The JSON route is more expressive and is what the example script uses: on exit 0, Claude Code reads a hookSpecificOutput object rather than a top-level "decision": "block" field. That top-level field exists in the hook system, but it belongs to different events (UserPromptSubmit, PostToolUse); for PreToolUse it is simply ignored, which is the single most common reason a hook that looks correct never actually blocks anything.
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Database writes are not allowed"
}
}
permissionDecision accepts allow, deny, ask, or defer, and permissionDecisionReason is the human-readable explanation. A separate updatedInput field can rewrite the tool’s arguments instead of outright blocking it, which is useful for stripping a flag rather than refusing the whole command.
Step 4: the timeout behavior that catches people out
A hook that times out does not fail closed. For command, http, and mcp_tool hooks, a timeout falls through to the normal permission flow — meaning the command can still run if the user’s permission mode would otherwise allow it. This is the opposite of what most people assume a 30-second timeout is for, and it means a hook calling out to a slow external service (a policy API, a vector lookup) is not a safety net on its own; treat the timeout as a liveness setting, not a security boundary. Agent SDK callback hooks behave differently and do block on timeout, so the two mechanisms are not interchangeable guarantees.
To actually verify the setup, run two commands through Claude Code: one that should trip the rule (rm -rf /tmp/scratch) and one that should not (ls). The transcript shows the hook-error or deny notice immediately after the matched call, and claude --debug prints the raw hook stdin/stdout if the decision is not what you expected.
Mistakes that let a command through anyway
| Mistake | What actually happens | Fix |
|---|---|---|
Script saved without chmod +x | The hook returns a non-blocking error (the “other exit code” row above), so the command still runs | Run chmod +x on every hook script before committing it |
Returning top-level "decision": "block" from a PreToolUse hook | Silently ignored; the field only applies to UserPromptSubmit and PostToolUse | Use hookSpecificOutput.permissionDecision instead |
| Writing a matcher that unintentionally contains a regex metacharacter | Claude Code switches from exact match to regex matching, which can match more — or fewer — tools than intended | Use ^Bash$ when you need a strict whole-string match |
Setting only the if field and leaving the matcher as "*" expecting it to narrow things down on its own | Both the matcher and if must match before the handler runs, so a loose matcher plus a strict if still fires on every tool call — it just usually passes | Set the matcher to the specific tool name as well, so the handler is not invoked (and does not add latency) on unrelated tools |
| Relying on the hook timeout to block risky commands under load | A timed-out command hook falls through to normal permissions and does not block | Keep hook logic fast and local, or treat it as advisory rather than a hard gate |
Where this fits with a broader guardrail strategy
A PreToolUse hook is a last line of defense at the exact moment a command is about to run, which makes it a good complement to, not a replacement for, policy set earlier in the pipeline. For a wider view of where rule-based blocking like this sits next to model-level safety behavior, see our breakdown of what an AI guardrail actually is. If the goal is specifically keeping infrastructure-as-code changes safe rather than ad hoc shell commands, the patterns in writing Terraform and infrastructure-as-code configs with AI prompts and in configuring Gitleaks as a pre-commit hook cover the adjacent problem of catching mistakes before they reach a shell at all. Teams running scheduled or unattended Claude Code sessions, as in scheduling a recurring Claude API call with cron, have the strongest reason to add a hook like this, since nobody is watching the transcript live to catch a bad command by hand.
None of this requires trusting a single layer. A hook that blocks on an exact string match will miss a cleverly obfuscated command, which is why the instructions-file checklist for AI coding assistants and a PreToolUse hook are meant to be used together: one shapes what the model is likely to propose, the other enforces what is allowed to actually execute.
Keeping the hook itself from becoming the problem
Treat the hook script like production code, because at the moment it runs it has more authority than the person using Claude Code: a bug in the grep pattern that matches too narrowly lets the exact command it was written for through, and a pattern that matches too broadly blocks legitimate work and trains the team to disable the hook instead of fixing it. Keep the matching logic in version control next to the project it protects, review changes to it the same way you would review a change to a CI gate, and add a short comment above each pattern explaining the incident or the risk it is there to stop — six months later, nobody remembers why curl | sh specifically is on the list.
It also helps to log every denial somewhere outside the transcript, even if that is just appending a line to a file with date, the blocked command, and the reason. A hook that fires often on the same command is telling you the underlying workflow needs a safer default, not just a block rule; a hook that never fires at all is worth testing again, since a typo in the matcher can leave it silently inert for months.



