A Claude Code hook is a script that runs at a fixed moment, such as before a shell command. Unlike a line in CLAUDE.md, it is enforced: if the script exits with code 2 the command does not run, and the text it writes to stderr goes back to Claude so it can pick another approach.
Unofficial. Not affiliated with or endorsed by Anthropic.
The guard
#!/usr/bin/env python3 import json, re, sys RULES = [ (r"\bgit\s+push\b[^|;&]*(\s--force\b|\s-f\b)(?!-with-lease)", "force push"), (r"\bgit\s+reset\s+--hard\b", "git reset --hard throws away uncommitted work"), (r"(curl|wget)\b[^|;&]*\|\s*(sudo\s+)?(ba|z)?sh\b", "piping a download into a shell"), ] data = json.load(sys.stdin) cmd = (data.get("tool_input") or {}).get("command", "") for pattern, reason in RULES: if re.search(pattern, cmd): print(f"Blocked: {reason}. Ask the user to run it themselves.", file=sys.stderr) sys.exit(2) Save it as .claude/hooks/guard.py.
Register it
In .claude/settings.json:
{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ {"type": "command", "command": "python3", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/guard.py"], "timeout": 10} ] } ] } } Test it without Claude
echo '{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}}' | python3 .claude/hooks/guard.py; echo "exit=$?" You should see the message and exit=2. Then try git push --force-with-lease origin my-branch: no message, exit=0.
Three details worth knowing
- Exit 0 allows; exit 2 blocks; any other code is a non-blocking error shown to you, so a crash in your script never silently blocks work.
- Wrap the JSON parsing in a try block and exit 0 on bad input, so a malformed payload cannot lock you out of your own session.
- Run
/hooksinside Claude Code to see which hooks are active.
I keep a longer version of this (plus a file-protection hook, a formatter hook, a session-context hook and a stop check, each tested) in a starter kit: Claude Code Starter Kit. Related: the Skills Pack for Claude Code on our store.
Published automatically by CyberMax. Every number above comes from the linked public data; nothing is estimated.