Skip to content
◀ Blog

How to block dangerous commands in Claude Code

Add deny rules to settings.json, then a PreToolUse hook on Bash that reads the command from stdin and denies destructive ones before they run.

Riley Hilliard8 min read

agentsclaude-code

To block dangerous commands in Claude Code, use two layers: permissions.deny rules in .claude/settings.json for the worst exact commands, and a PreToolUse hook on the Bash tool that inspects every command before it runs and denies the destructive ones. A line in CLAUDE.md saying “never force push” is a request, and the model can forget it. Deny rules and hooks are enforced by Claude Code itself.

The hook needs one more thing to work well: its deny message has to tell the agent to ask you instead of trying the same command another way. Regex matching on command text catches accidents, and an agent that rephrases around a block will get past it. The examples below are the real hooks in the steamfield.io repository.

How do you block dangerous commands in Claude Code?

Start with deny rules, because they need no script. Ours include:

"deny": [
  "Bash(rm -rf /)",
  "Bash(rm -rf ~)",
  "Bash(git push --force)",
  "Bash(git push --force *)",
  "Bash(git push -f)",
  "Bash(git push -f *)",
  "Bash(git reset --hard)",
  "Bash(git reset --hard *)",
  "Bash(git commit *--no-verify*)"
]

Claude Code checks deny rules before ask and allow rules, and they still apply with hooks turned off. Two limits push you toward a hook. First, a Bash rule matches the command text, so the permissions docs list git -C . push origin main and bash -c 'rm -rf build/' among forms a rule like Bash(git push *) or Bash(rm *) doesn’t stop. Second, a broad wildcard denies too much: our .claude/README.md notes that Bash(rm -rf /*) “would match every rm -rf /some/abs/path,” and a deny rule can’t be overridden by an allow rule. So the deny list stays exact, and the hook handles the variations.

A PreToolUse hook runs before the tool call. Claude Code sends it a JSON payload on stdin with tool_name and tool_input (for Bash, tool_input.command). The hook can block in one of two ways:

  • Exit with code 2. Claude Code blocks the call and shows Claude the hook’s stderr as the reason.
  • Exit 0 and print a JSON object with hookSpecificOutput.permissionDecision set to "deny" and a permissionDecisionReason, which is shown to Claude.

Exit 0 with no output means the hook has no opinion, and the normal permission flow continues. A hook’s "allow" doesn’t override a matching deny rule, and a blocking hook takes effect even when an allow rule would have let the command through.

What does a PreToolUse hook look like?

The wiring goes in .claude/settings.json. The matcher is the tool name; Bash matches exactly, and Edit|Write matches either tool:

"PreToolUse": [
  {
    "matcher": "Bash",
    "hooks": [
      {
        "type": "command",
        "command": "bash \"${CLAUDE_PROJECT_DIR}/.claude/hooks/block-destructive.sh\"",
        "timeout": 10
      }
    ]
  }
]

${CLAUDE_PROJECT_DIR} is the project root, so the hook runs no matter which directory the agent has cd’d into. Calling it through bash means the script doesn’t need its executable bit. The timeout is in seconds; command hooks default to 600, which is far too long for a check that runs on every shell call.

A minimal hook that stops force pushes, using jq to read the payload:

#!/usr/bin/env bash
# PreToolUse (Bash): deny git push --force and -f.
cmd=$(jq -r '.tool_input.command // empty')
if grep -qE 'git[[:space:]]+push[[:space:]](.*[[:space:]])?(-f|--force)([[:space:]]|$)' <<<"$cmd"; then
  echo "Force push blocked. Ask the user; do not rephrase the command." >&2
  exit 2
fi
exit 0

It denies git push --force origin main and git push -f, and allows git push --force-with-lease and a branch named feature-f. We checked all four by piping payloads into it.

Our production version returns JSON instead of exiting 2, so the reason can carry a suggestion. Its helper prints:

printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":%s}}\n' \
  "$(json_quote "$1")"

and a force push gets this reason back:

BLOCKED: Force push rewrites remote history.

Ask the user first. If it is needed, use --force-with-lease.
Never work around this block.

The last line stops the agent from retrying the command another way. The project’s AGENTS.md says the same thing in its Guardrails section (“A block means ask the user; never rephrase a command or use another tool to bypass it”), and the reason repeats it at the moment the agent needs it.

Which commands should you block?

Block commands that destroy work or data with no way back. Our list, from .claude/hooks/_destructive-patterns.sh, covers:

Area Denied
Filesystem rm of /, ~, ., .. or a bare *; find -delete; dd or mkfs on a disk; chmod 777
Local git git reset --hard, forced git clean, git checkout ., git restore ., git branch -D, dropping the stash
Remote git Force push, pushes that delete remote branches (--mirror, --delete, :<ref>), --no-verify on commit or push
Everything else sudo, a download piped into a shell, DROP TABLE, docker compose down -v, terraform destroy, kubectl delete

To stop Claude Code from force pushing without blocking the safe version, the pattern allows --force-with-lease and --force-if-includes. The git rules also only match the command being run, so a commit message or PR body that mentions git reset --hard goes through. The script splits a command line on ;, &&, | and friends, then checks whether git (after wrappers like sudo, env or timeout) is the command word of each piece. It also unpacks bash -c '...' payloads and checks them the same way.

Leave ordinary deletes alone. rm -rf dist is something an agent runs all day, and a guard that prompts on it teaches you to approve without reading.

How do you stop secrets from being written to files?

Add a second PreToolUse hook with the matcher Edit|Write that reads the text being written and denies credential-shaped strings. Ours, detect-secrets.sh, takes the text from tool_input.content for Write and tool_input.new_string for Edit, then checks high-confidence formats only: AWS access keys (AKIA plus 16 characters), GitHub and GitLab tokens, Slack tokens and webhooks, Stripe keys, Anthropic and OpenAI keys, PEM private keys, JWTs, and database URLs with an embedded password.

Three choices keep it usable:

  • It denies any write to .env, .env.* or .envrc, but allows .env.example, .env.sample and .env.template. The agent writes variable names to the example file and asks you for real values.
  • Matches that look like placeholders (your-, changeme, example, xxxx) are ignored by the generic rule, and a line containing pragma: allowlist secret is skipped, for test fixtures that must look real.
  • The deny reason names the kind of secret, never the matched text, so the key doesn’t get echoed back into the transcript.

Pair the hook with deny rules on reading env files, such as Read(./.env) and Read(./**/.env), so real values don’t reach the agent’s context in the first place.

What can’t a regex hook catch?

Anything that hides the command from the text. Our .claude/README.md says the guards are for “accidents, not adversaries,” and “quoting, eval, aliases and scripts that run a command indirectly get past them.” We confirmed one case by piping it in: r=rm; $r -rf ~ produces no deny, because no segment’s command word is rm. A Python one-liner calling shutil.rmtree or a Makefile target that runs git push -f gets past it the same way.

It also gets false positives. Rules outside git match raw command text, so a shell heredoc that writes documentation mentioning rm -rf ~ is denied. The README’s advice is to write such docs with the Edit or Write tool instead. While drafting this post, a test loop of ours that only carried those strings as data was blocked for the same reason.

Treat the hook as a guard against mistakes. For a hard boundary, Claude Code’s permissions docs point to sandboxing, which sets filesystem and network limits that don’t depend on command text.

How do you test a hook without running the command?

Pipe it a payload. A hook is a script that reads JSON from stdin, so you can test it with echo and never execute the command it judges:

echo '{"tool_name":"Bash","tool_input":{"command":"git push --force"}}' | bash .claude/hooks/block-destructive.sh

That prints the deny JSON. A command the hook allows prints nothing.

For each rule, test one command that must be denied and one near miss that must pass, such as a force push and a commit message that mentions one. Our smoke.sh does that for both guards, then checks that settings.json parses and still wires block-destructive.sh. It builds the dangerous strings from pieces (f='git push --'force) so the test file itself doesn’t trip the secret or command guards when an agent edits it.

These hooks came from Stacks, the project starter we build, which scaffolded this site. Its agent-ops fragment writes the hooks, the deny rules and smoke.sh into a project, and stacks verify runs the smoke test as its hooks-smoke step.

Run /hooks inside Claude Code to see what is wired, and if a hook misbehaves, set "disableAllHooks": true in .claude/settings.local.json while you fix it. The deny rules keep applying while hooks are off.