Claude Code hooks: block dangerous commands

A working PreToolUse hook, how to register and test it, and where it stops being enough.

Claude Code can run shell commands for you. Most of the time that is the point. Once in a while it is a command you cannot take back: a recursive delete, a force push, a dropped table. A hook is a small program that Claude Code runs before a tool call, and it can say no. This guide builds one that blocks dangerous Bash commands, shows how to wire it up, and explains where such a hook stops being enough.

What a PreToolUse hook is

Hooks are commands that Claude Code runs at fixed points of its work. PreToolUse fires before a tool runs, for example before Claude executes a Bash command. Your script receives the event as JSON on stdin. Two fields matter here:

The script answers in one of two ways. The simple way is the exit code: exit code 2 blocks the call, and whatever you wrote to stderr is handed to Claude as feedback, so it knows why and can pick another approach. Exit code 0 means "no decision": the normal permission flow continues. Any other non-zero exit code, without valid JSON on stdout, does not block on most events, the action proceeds. So a crash in your script is not a lock. Remember that when you write one.

A hook that blocks dangerous commands

Save this as ~/.claude/hooks/block_dangerous.py. It reads the event, ignores everything that is not Bash, and refuses a short list of patterns. If the input cannot be read at all, it blocks as well (fail closed).

#!/usr/bin/env python3
import json
import re
import sys

RULES = [
    (r"\brm\s+(-\w*r\w*f|-\w*f\w*r)\b", "recursive force delete"),
    (r"\bgit\s+push\b.*(--force(?![-\w])|\s-f\b)", "force push"),
    (r"\bgit\s+reset\s+--hard\b", "git reset --hard"),
    (r"\bdrop\s+(table|database)\b", "SQL drop"),
    (r"\bdocker\s+system\s+prune\b", "docker system prune"),
]

try:
    event = json.load(sys.stdin)
except Exception:
    print("block_dangerous: unreadable hook input", file=sys.stderr)
    sys.exit(2)

if event.get("tool_name") != "Bash":
    sys.exit(0)

command = event.get("tool_input", {}).get("command", "")
for pattern, reason in RULES:
    if re.search(pattern, command, re.IGNORECASE):
        print("Blocked: %s. Ask the user, or use a safer command." % reason, file=sys.stderr)
        sys.exit(2)
sys.exit(0)

The patterns are examples, not a finished list. Add the commands that would hurt you: the database client you use, the cloud CLI that can delete a project, the backup tool with a prune command.

Register it in settings.json

Hooks live in a settings file. ~/.claude/settings.json applies to all your projects. .claude/settings.json inside a repository is meant to be committed, so everyone who clones the repository gets the same permissions and hooks. .claude/settings.local.json is for your own, uncommitted overrides. Add:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "python3 ~/.claude/hooks/block_dangerous.py" }
        ]
      }
    ]
  }
}

The matcher limits the hook to the Bash tool. Start a new session after you change the file, then test it for real: ask Claude to run git reset --hard in a throwaway repository. It should be refused, and Claude should explain why.

Test the script without Claude

A hook is just a program, so test it like one. Pipe a fake event in and read the exit code:

echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf ./build"}}' | python3 ~/.claude/hooks/block_dangerous.py; echo "exit: $?"
echo '{"tool_name":"Bash","tool_input":{"command":"ls -la"}}' | python3 ~/.claude/hooks/block_dangerous.py; echo "exit: $?"

The first should print the block message and exit: 2, the second exit: 0. Keep a small list of commands that must be blocked and commands that must pass, and run it whenever you edit a rule. A hook that wrongly blocks harmless commands will get switched off by you within a week, which is worse than no hook.

The JSON alternative

Instead of an exit code you can exit 0 and print JSON. For a PreToolUse hook, the decision goes inside hookSpecificOutput:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Force pushes are not allowed here."
  }
}

With deny, Claude Code cancels the tool call and feeds permissionDecisionReason back to Claude. The other values are allow and ask; an allow from a hook does not override deny rules from your settings. Use exit 2 for a plain block with a message, JSON when you want structured control.

Why this is a real lock

A rule in CLAUDE.md is a request. A hook is enforced by the program around the model. The docs state that a hook returning permissionDecision: "deny" blocks the tool even in bypassPermissions mode or with --dangerously-skip-permissions. That is exactly why people who let Claude run without prompts add them.

What a command-text hook cannot do

Treat the hook as one layer. Keep backups and snapshots behind it, so a command that slips through can be undone. If you would rather start from a tested hook than a five-line sketch, the open-source denylist-hook covers a much longer list, including commands hidden behind sudo, bash -c and docker exec, and ships its own tests.

Want the whole safety setup, hooks plus backups, templates and rules for what Claude may never do? The handbook covers it: Pocket Server.