A PreToolUse hook for Claude Code that blocks dangerous bash commands. Essential when running with --dangerously-skip-permissions (headless/CI mode) to prevent Claude from executing destructive operations.
| Category | Examples |
|---|---|
| Destructive file ops | rm -rf, shred, dd, mkfs, fdisk, truncate |
| System control | reboot, shutdown, halt, poweroff, kill -9, killall |
| Dangerous permissions | chmod 777, chmod -R, chown root |
| Service disruption | systemctl stop/disable |
| Firewall tampering | iptables -F, ip6tables -F, ufw disable |
| Remote code execution | curl | sh, wget | bash |
| SSH key tampering | ssh-keygen, writes to .ssh/ |
| Git destructive ops | push --force, push to main/master, reset --hard, clean -f |
| Database destruction | DROP DATABASE, DROP TABLE, TRUNCATE TABLE |
| Docker destructive ops | rm -f, system prune, volume rm, network rm |
| Credential exfiltration | env | curl, cat .env | nc, env to /dev/tcp |
| Package hijacking | npm publish, pip install from URL or custom registry |
| Fork bombs | :(){ :|: & };: pattern |
- jq — used to parse hook input and format deny responses
# Debian/Ubuntu sudo apt install jq # macOS brew install jq # Arch sudo pacman -S jq
mkdir -p ~/.claude/hooks
cp block-dangerous-commands.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/block-dangerous-commands.shAdd the following to ~/.claude/settings.json (create if it doesn't exist):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/block-dangerous-commands.sh"
}
]
}
]
}
}If you already have a settings.json, merge the hooks key into your existing config.
Start Claude Code and try a blocked command:
> run `rm -rf /tmp/test`
You should see Claude refuse with: BLOCKED: rm -rf (recursive force delete)
The script uses a simple chk function for each rule:
chk 'REGEX_PATTERN' "BLOCKED: human-readable reason"- Add rules: add a new
chkline with a regex and reason - Remove rules: delete or comment out the
chkline - Block sudo entirely: uncomment the
sudoline in the System Administration section
# Block access to production database
chk '\bpsql\b.*prod' "BLOCKED: direct access to production database"- Claude Code calls this script before every
Bashtool invocation - The script receives JSON on stdin:
{"tool_name":"Bash","tool_input":{"command":"..."}} - Each
chkcall tests the command against a regex pattern - If matched, it outputs a JSON deny decision and Claude skips the command
- If no patterns match, the script exits cleanly and Claude proceeds
Public domain — use freely.