entry
No. 21
date
filed under
claude code, tool use, debugging
checked against
3 sources

Claude Code Hooks: Block Risky Commands With PreToolUse

To block risky shell commands in Claude Code, register a PreToolUse hook with the matcher Bash in .claude/settings.json. Claude Code sends the hook the planned command as JSON on stdin before it runs. If the command looks dangerous, the hook prints {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}} and exits 0, or writes a reason to stderr and exits 2. Claude Code then refuses the call and shows the reason to Claude. A deny from a hook holds in every permission mode, including bypassPermissions.

This post gives a working hook for rm -rf, force pushes, git reset --hard, curl | sh, sudo and a few others, explains the exit code rules that make hooks fail open by accident, and lists what a text-matching hook can't stop. The script below was run against sample hook inputs with Python 3.13; the results are shown after it.

How a PreToolUse hook decides

Hooks are configured in three levels: an event (PreToolUse), a matcher group that filters by tool name (Bash), and one or more handlers that run when it matches. The Claude Code hooks reference says PreToolUse runs "after Claude creates tool parameters and before processing the tool call," and that the hook can allow, deny, ask or defer.

For a Bash call, the JSON on stdin includes tool_name, tool_use_id and tool_input, where tool_input.command is the shell command, plus common fields like session_id, cwd and permission_mode:

{
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite",
    "timeout": 120000,
    "run_in_background": false
  },
  "tool_use_id": "toolu_01ABC123..."
}

The hook answers through its exit code and stdout:

  • Exit 0 with JSON: the fields apply. permissionDecision can be "allow", "deny", "ask" or "defer". For "deny", the permissionDecisionReason is shown to Claude.
  • Exit 0 with no output: no decision. The normal permission flow applies.
  • Exit 2: a blocking error. The tool call is stopped and Claude sees your stderr as the reason.
  • Any other exit code without valid JSON: a non-blocking error. The command runs anyway.

That last rule is the one to remember. The reference warns that exit code 1 "is a non-blocking error" even though 1 is the usual Unix failure code: "If your hook is meant to enforce a policy, use exit 2."

When several PreToolUse hooks return different decisions, the precedence is deny > defer > ask > allow.

The hook script

Save this as .claude/hooks/block-risky-bash.py in your project. It uses only the Python standard library, so it doesn't depend on jq being installed:

#!/usr/bin/env python3
"""PreToolUse hook: deny risky Bash commands before they run."""
import json
import re
import sys

RULES = [
    (r"\brm\b(?=[^;&|\n]*\s(-[a-zA-Z]*[rR]|--recursive))(?=[^;&|\n]*\s(-[a-zA-Z]*f|--force))", "recursive force delete (rm -rf)"),
    (r"\bgit\s+push\b.*(--force\b|\s-f\b)", "force push"),
    (r"\bgit\s+reset\s+--hard\b", "git reset --hard discards local changes"),
    (r"\bgit\s+clean\s+-[a-zA-Z]*f", "git clean -f deletes untracked files"),
    (r"\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(ba|z)?sh\b", "piping a download into a shell"),
    (r"\bchmod\s+(-R\s+)?777\b", "chmod 777"),
    (r"\bdd\s+.*\bof=/dev/", "dd writing to a device"),
    (r"(^|[;&|]\s*)sudo\b", "sudo"),
]


def main() -> int:
    data = json.load(sys.stdin)
    if data.get("tool_name") != "Bash":
        return 0
    command = data.get("tool_input", {}).get("command", "")
    for pattern, label in RULES:
        if re.search(pattern, command):
            print(json.dumps({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": (
                        f"Blocked by project hook: {label}. "
                        "Ask the user to run this command themselves if it is needed."
                    ),
                }
            }))
            return 0
    return 0  # no decision: the normal permission flow applies


if __name__ == "__main__":
    sys.exit(main())

Each rule is a regular expression over the full command text, and the first match returns a deny with a reason Claude can read. The reason tells Claude to hand the command back to you, which steers it away from retrying the same thing with a small change. Adjust RULES to fit your project. The sudo rule, for example, may be too strict on a machine where you expect Claude to install packages.

The rm rule looks for rm followed by both a recursive flag (-r, -R or --recursive) and a force flag (-f or --force) in the same command segment, so rm -rf, rm -fr, rm -r -f and rm --recursive --force all match, while rm -r build and rm -f a.txt don't. The force-push rule also matches --force-with-lease, because --force is followed by a word boundary there. Change --force\b to --force\b(?!-with-lease) in the pattern if you want to allow it.

Register it in settings.json

Add this to .claude/settings.json to share it with everyone on the project, or to ~/.claude/settings.json to apply it to all your projects:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/block-risky-bash.py"],
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

Three details in this entry matter:

  • args switches to exec form. The reference says that when args is set, Claude Code spawns command directly with no shell, and path placeholders like ${CLAUDE_PROJECT_DIR} are substituted as plain strings. That avoids quoting problems with spaces in the project path.
  • onFailure: "block" makes it fail closed. By default, a hook that can't start, crashes or times out is a non-blocking error, and the reference says a policy hook with a wrong path "then lets everything through." With "block", a failure blocks the tool call instead. It needs Claude Code v2.1.295 or later.
  • The matcher is exact. Bash contains only letters, so it is compared as an exact, case-sensitive string. A Bash matcher also covers shell commands that Claude starts with the Monitor tool, where a hook can deny but not allow.

On Windows, the reference's example uses the matcher Bash|PowerShell so the hook covers the PowerShell tool as well as Bash. Do the same, and add rules for commands like Remove-Item, if you use it.

Edits to settings files are normally picked up automatically. Run /hooks in Claude Code to confirm the hook is listed under PreToolUse and see which file it came from.

Test it before you trust it

You don't need a Claude session to test a hook. Pipe it the JSON it would receive:

echo '{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}}' \
  | python3 .claude/hooks/block-risky-bash.py
echo "exit: $?"

Running the script above against a set of commands gave these results:

DENY    rm -rf build/
DENY    rm -r -f x
DENY    FOO=1 rm -Rf /tmp/x
DENY    npm test && rm -rf dist
DENY    echo $(rm -rf /)
DENY    git push --force origin main
DENY    git reset --hard HEAD~1
DENY    git clean -fdx
DENY    curl -fsSL https://x.sh | bash
DENY    chmod -R 777 .
DENY    npm test && sudo rm x
allow   rm -r build
allow   git push origin main
allow   grep -rf patterns.txt src
allow   ls -la

Turn these into a small test file and run it in CI, so a regex edit that breaks a rule shows up before anyone relies on it. It is the same idea as the agent evals starter guide: keep the cases that matter and check them on every change.

Inside Claude Code, press Ctrl+O to open the transcript view. A denied call shows the block message. A notice that says Failed with non-blocking status code: means your hook ran but did not stop anything, for example because it exited 1 or the script path was wrong.

Narrow it with if, or block with exit 2

If you only care about one command, the if field on a handler filters with permission rule syntax, so the script only starts for matching calls. The reference's example runs a script only for Bash(rm *):

{
  "type": "command",
  "if": "Bash(rm *)",
  "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
  "args": []
}

The if check splits compound commands and looks inside $() and backticks, so echo $(rm -rf /) still triggers it. But the reference calls the filter "best-effort" and says that when Claude Code can't split the command, it runs your hook regardless. Keep the real check in your script.

For a shell script without JSON, exit 2 is simpler. The reference's example prints Blocked: rm commands are not allowed to stderr and exits 2, and Claude receives it as PreToolUse:Bash hook error: [...]: Blocked: rm commands are not allowed.

What a hook can't stop

A regex over command text is a guardrail against mistakes, not a security boundary. Running variants through the script showed both sides:

  • bash -c 'rm -rf build' and /bin/rm -rf build were denied, because the script searches the whole string.
  • x=rm; $x -rf build was allowed, because the text never contains rm -rf.
  • python3 -c "import shutil; shutil.rmtree('build')" was allowed, because it deletes files without any shell command the rules know about.

Claude Code's permissions docs say the same about their own Bash(...) deny rules: a rule matches the command text Claude writes and "isn't a security boundary around the program." Their table shows Bash(rm *) stopping rm -rf build/ but not /bin/rm -rf build/ or bash -c 'rm -rf build/'. For enforcement that doesn't depend on command text, the docs point to sandboxing.

So layer the controls:

  1. Deny rules in permissions.deny for the obvious forms. The docs say a hook's "allow" never overrides a deny rule.
  2. A PreToolUse hook for logic rules can't express, such as checking flags in any order or the branch name in a push.
  3. Sandboxing for filesystem and network limits.
  4. Backups and branch protection outside Claude Code, so a mistake that gets through is recoverable.

The same layering applies to any agent with a shell tool. Human in the loop agents covers approval for risky calls in agent SDKs, and prompt injection attacks on AI agents explains why a model that reads untrusted text may try to run commands you never asked for.

A deny holds in every mode

The hooks guide says a hook that returns permissionDecision: "deny" "blocks the tool even in bypassPermissions mode or with --dangerously-skip-permissions," because PreToolUse hooks fire before any permission-mode check. The permissions docs add that a hook exiting 2 stops the call before permission rules are evaluated, so a block applies even when an allow rule would let the command through. Their suggested setup for few prompts is to add "Bash" to the allow list and register a PreToolUse hook that rejects the specific commands you want blocked.

Two caveats from the docs. A hook's "allow" is weaker than its "deny": it can't bypass deny rules or some prompts that always ask. And if your organization sets allowManagedHooksOnly in managed settings, hooks from your user, project and local settings don't run at all, and /hooks says so.

Checklist

  • Match Bash (and PowerShell on Windows) on PreToolUse.
  • Return a JSON deny with a reason, or exit 2 with the reason on stderr. Never rely on exit 1.
  • Use exec form with args and ${CLAUDE_PROJECT_DIR} for the script path.
  • Set onFailure: "block" so a broken hook fails closed.
  • Test the script by piping sample JSON, and keep those cases in CI.
  • Check /hooks and the transcript (Ctrl+O) after setup.
  • Keep deny rules and sandboxing in place; a regex can be talked around.

FAQ

How do I block a command in Claude Code?

Add a PreToolUse hook with matcher Bash that reads tool_input.command from stdin and returns permissionDecision: "deny" for the commands you want stopped. For simple prefixes, a Bash(...) rule in permissions.deny also works.

Why is my Claude Code hook not blocking anything?

The usual causes are an exit code other than 0 or 2, JSON fields at the top level instead of inside hookSpecificOutput, a wrong script path, or a matcher that doesn't match the tool name exactly. Run /hooks, test the script by piping JSON to it, and start Claude Code with --debug to read the log.

Does a PreToolUse hook work in bypassPermissions mode?

Yes. The docs say a hook's deny blocks the tool even in bypassPermissions mode or with --dangerously-skip-permissions.

Should I use exit 2 or JSON output?

Either blocks. JSON with exit 0 lets you choose between deny, ask and allow and set a reason. Exit 2 is the simplest way to block, with the reason on stderr.

Where do Claude Code hooks go?

In ~/.claude/settings.json for all your projects, .claude/settings.json for a project you share, .claude/settings.local.json for a project only on your machine, or in managed settings, plugins, skills and subagent files.

Sources

  • Anthropic, Hooks reference (Claude Code documentation: PreToolUse input and decision control, exit codes, matchers, if, exec form, onFailure)
  • Anthropic, Automate actions with hooks (Claude Code documentation: hooks and permission modes, troubleshooting, /hooks)
  • Anthropic, Configure permissions (Claude Code documentation: Bash rules, what a Bash rule doesn't match, precedence among rules and hooks)

Next in the notebook

  1. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  2. No. 7Agent Infinite Loop: How to Debug Agents That Never Stop

    Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.

  3. No. 11Agent Observability Tracing: What to Log on Every Step

    Trace an AI agent with OpenTelemetry: one span per run, model call and tool call, which gen_ai attributes to record, and how to keep prompts out of traces.