Block Dangerous Commands Before They Run with PreToolUse Hooks
The PreToolUse hook fires before every tool call. Because it supports blocking via exit code 2, you can use it to intercept commands that should never run automatically, adding a programmable safety layer on top of standard permission rules.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/check-dangerous.sh"
}
]
}
]
}
}
The hook script receives the tool input as JSON on stdin. Inspect the command and exit with code 2 to block it:
#!/usr/bin/env bash
input=$(cat)
cmd=$(echo "$input" | jq -r '.command // empty')
if echo "$cmd" | grep -qE '(rm -rf /|DROP TABLE|git push --force)'; then
echo '{"decision":"block","reason":"Blocked dangerous command"}'
exit 2
fi
This is more granular than static permission rules. You can apply context-aware logic: block git push --force to main but allow it to feature branches, or block destructive commands outside a specific working directory.
The matcher field uses regex, so "Bash" matches all shell calls, "Edit|Write" matches file-modifying tools, and "mcp__.*" matches every MCP tool call.
Add this config to ~/.claude/settings.json for a global safety net, or to .claude/settings.json for project-specific rules.
A PreToolUse hook is a programmable checkpoint that runs before every tool call, giving you fine-grained control over what Claude can actually do.
Log in to leave a comment.
The autoUpdatesChannel setting pins Claude Code to a stable release track that skips versions with major regressions.
The language setting makes Claude respond in your preferred language by default, across every session and project.
The attribution setting lets you customize or completely remove Claude's Co-Authored-By trailer from git commits and pull requests.