How to block rm -rf in Claude Code with a PreToolUse hook
Short version: add two deny rules, save a small hook script to .claude/hooks/, and register it under PreToolUse with the matcher Bash. The hook sees the full command before it runs and answers "permissionDecision": "deny" for any recursive forced delete.
Why a deny rule alone isn’t enough
Claude Code’s permission rules are the first thing to reach for, and you should keep them. A Bash deny rule matches the command text Claude writes, after Claude Code splits compound commands and strips wrappers, so Bash(rm -rf *) does catch cd x && rm -rf build and timeout 5 rm -rf build. It still isn’t a security boundary around the program. The permissions docs say a deny or ask rule “covers the invocation Claude usually produces and isn’t a security boundary around the program.” Their examples of misses are /bin/rm -rf build/ and bash -c 'rm -rf build/'. A permission rule also won’t match a different flag spelling such as rm -fr build or rm -r -f build. To inspect the full command text with your own logic before it runs, they point to a PreToolUse hook.
Step 1: add the cheap deny rules
These catch the common spelling with no script at all. They go in .claude/settings.json (shared with the repo) or ~/.claude/settings.json (all your projects). The full file with the hook is in step 3.
{
"permissions": {
"deny": [
"Bash(rm -rf *)",
"Bash(rm -fr *)"
]
}
}Step 2: save the hook script
Save this as .claude/hooks/block-rm-rf.sh and run chmod +x .claude/hooks/block-rm-rf.sh. It needs jq, like the examples in the official hooks reference.
#!/usr/bin/env bash
# block-rm-rf.sh: deny recursive + forced rm (rm -rf, rm -fr, rm -r -f, rm --recursive --force).
# Works as a Claude Code PreToolUse hook and as a Cursor beforeShellExecution hook.
# Needs jq.
input=$(cat)
event=$(jq -r '.hook_event_name // empty' <<<"$input")
cmd=$(jq -r '.tool_input.command // .command // empty' <<<"$input")
is_rm_rf() {
# Split into simple pieces at ; & | ( ) backticks, quotes and newlines,
# so "cd x && rm -rf y" and bash -c "rm -rf y" are both seen.
# Flag-only wrappers: sudo, doas, xargs, command, env, nohup, time, exec, plus VAR=value.
# nice, timeout, stdbuf and ionice also take a numeric class or duration, e.g. timeout 5 or nice -n 10.
printf '%s\n' "$1" | tr ';&|()`"'"'" '\n' | while IFS= read -r seg; do
if grep -Eq '^[[:space:]]*((sudo|doas|xargs|command|env|nohup|time|exec|[A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*)([[:space:]]+-[^[:space:]]+)*[[:space:]]+|(nice|timeout|stdbuf|ionice)([[:space:]]+-[^[:space:]]+|[[:space:]]+[0-9]+([.][0-9]+)?[smhd]?)*[[:space:]]+)*([^[:space:]]*/)?rm[[:space:]]' <<<"$seg" &&
grep -Eq '(^|[[:space:]])(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)([[:space:]]|$)' <<<"$seg" &&
grep -Eq '(^|[[:space:]])(-[a-zA-Z]*f[a-zA-Z]*|--force)([[:space:]]|$)' <<<"$seg"; then
echo hit
break
fi
done | grep -q hit
}
reason="Blocked: recursive forced delete (rm -rf). Delete specific paths without -f, or ask the user to run it."
if is_rm_rf "$cmd"; then
if [ "$event" = "beforeShellExecution" ]; then
jq -n --arg r "$reason" '{permission: "deny", user_message: $r, agent_message: $r}'
else
jq -n --arg r "$reason" '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}'
fi
exit 0
fi
# No objection. Cursor expects a JSON answer; Claude Code treats silence as "no decision".
[ "$event" = "beforeShellExecution" ] && echo '{"permission": "allow"}'
exit 0What it does: it splits the command at ;, &, |, brackets, backticks and quotes, so cd /tmp && rm -rf ~ and bash -c "rm -rf ~" are checked piece by piece. A piece is blocked when it runs rm (also after wrappers such as sudo, nice, timeout, stdbuf, ionice, xargs, env or a VAR=x prefix, or by path like /bin/rm) with both a recursive flag (-r, -R, --recursive) and a force flag (-f, --force), in any order or cluster. Plain rm file, rm -r build and git rm -r --cached are left alone.
Step 3: register it in settings.json
{
"permissions": {
"deny": [
"Bash(rm -rf *)",
"Bash(rm -fr *)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm-rf.sh",
"timeout": 10
}
]
}
]
}
}If you already have a hooks or permissions block, add these entries to it instead of replacing it. The hooks reference uses ${CLAUDE_PROJECT_DIR} as a placeholder for the project root, so the path works from any subdirectory.
Step 4: test it without Claude
Hooks read JSON on stdin, so you can feed one a fake tool call:
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"cd /tmp && rm -rf ~"}}' \
| .claude/hooks/block-rm-rf.sh{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Blocked: recursive forced delete (rm -rf). Delete specific paths without -f, or ask the user to run it."
}
}A command it has no objection to, such as npm test, prints nothing and exits 0. Per the hooks reference, that means “no decision”, and Claude Code’s normal permission flow carries on. The script is checked with a suite of fake stdin payloads like this one, not inside a live Claude Code or Cursor session. Then restart Claude Code and run /hooks to check the hook is loaded.
JSON decision vs exit code 2
There are two documented ways to block from a PreToolUse hook. You can exit 0 and print hookSpecificOutput with permissionDecision: "deny" and a reason, which is what this script does. Or you can print a message to stderr and exit 2. Both stop the call. The JSON form lets you also return "ask" to hand the decision to a human. A hook that crashes with any other exit code doesn’t block the call, so test your script before relying on it.
The same script in Cursor
The script checks hook_event_name. When Cursor calls it as a beforeShellExecution hook, it reads .command and answers in Cursor’s format ({"permission": "deny", ...}). Register it in .cursor/hooks.json as shown in the force-push guide.
Limits
- It is a pattern check, not a sandbox. If the agent writes a script file containing
rm -rf ~and runsbash cleanup.sh, the hook only seesbash cleanup.sh. For untrusted work, use Claude Code’s sandboxing or a container as well. - It doesn’t cover
find . -delete,git clean -fdxorrsync --delete. Add rules for those if they matter in your repo. - It errs on the side of blocking.
git commit -m "cleanup rm -rf leftovers"is allowed, because after the quote split the leftover piece does not look like anrmcommand.git commit -m "rm -rf the old build"andgit log --grep="rm -rf"are denied, because the quote split leaves a piece that looks like anrmcommand. - Hooks run with your user’s permissions. Read any hook script, including this one, before installing it.