How to Block Dangerous Commands with Claude Code Hooks

You are currently viewing How to Block Dangerous Commands with Claude Code Hooks
Image created with Claude AI

Claude Code runs shell commands on your machine with your user permissions. Permission prompts help, but a long session, a tired click on “Yes”, or an unattended claude -p run in CI can still let rm -rf or git push --force through. Claude Code hooks fix this: a PreToolUse hook inspects every Bash command before it runs and denies the dangerous ones, no matter what you click.

In this tutorial you will write a small guard script, register it as a project hook, and verify that it blocks recursive forced deletes, force pushes, curl | bash installs and access to .env files, while normal commands pass through untouched.

Tested on: Ubuntu 24.04.5 LTS, Claude Code 2.1.332, GNU bash 5.2.21, jq 1.7.

The Problem

Out of the box, nothing stands between Claude and a destructive command except the permission prompt. Check which hooks are configured for your project:

cat .claude/settings.json
cat: .claude/settings.json: No such file or directory

No settings file, no hooks. If you allow Bash in an unattended run (for example claude -p "..." --allowedTools "Bash"), Claude can run any shell command it decides it needs. Most of the time that is fine. The one time it is not, you lose a directory or rewrite the history of main.

How Claude Code Hooks Work

A hook is a handler that Claude Code runs at a specific point of its lifecycle. For security, the important event is PreToolUse: it fires after Claude has prepared a tool call and before the tool runs. A command hook receives the call as JSON on stdin, for example:

{ "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }

The hook answers through its exit code and stdout:

  • Exit 0, no output: no decision. The normal permission flow applies (the hook does not approve anything).
  • Exit 0 with JSON containing hookSpecificOutput.permissionDecision: "allow", "deny", "ask" or "defer". A "deny" blocks the call and Claude sees your permissionDecisionReason.
  • Exit 2: blocks the call; Claude sees stderr as the reason.
  • Any other failure (crash, missing script, invalid JSON) is a non-blocking error: the command runs anyway, unless you set "onFailure": "block".

That last point matters for a security hook. We will use JSON output for clear reasons, and onFailure: "block" so a broken guard fails closed.

Prerequisites

  • Claude Code v2.1.295 or later (required for onFailure). Check with claude --version.
  • jq on your PATH (sudo apt install jq on Debian/Ubuntu).
  • A project directory where you run Claude Code. Hooks in .claude/settings.json can be committed, so the whole team gets the same guard.
  • Basic Bash. If you need a refresher on processing command output in scripts, see How To Store MySQL Result To Array From Bash.
claude --version
jq --version
2.1.332 (Claude Code)
jq-1.7

Step 1: Create the Guard Script

Create the hooks directory in your project root:

mkdir -p .claude/hooks

Save the following as .claude/hooks/guard-bash.sh:

#!/bin/bash
# .claude/hooks/guard-bash.sh - block destructive shell commands before Claude Code runs them
set -euo pipefail

COMMAND=$(jq -r '.tool_input.command // empty')

deny() {
  jq -n --arg reason "$1" '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: $reason
    }
  }'
  exit 0
}

# 1. Recursive delete with force (rm -rf, rm -fr, rm -r -f, rm --recursive --force)
if echo "$COMMAND" | grep -Eq '(^|[;&|[:space:]])rm[[:space:]]+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r|.*(-r|--recursive).*(-f|--force)|.*(-f|--force).*(-r|--recursive))'; then
  deny "Recursive forced delete is blocked by guard-bash.sh. Delete specific files instead."
fi

# 2. Force push (but allow --force-with-lease)
if echo "$COMMAND" | grep -Eq 'git[[:space:]]+push\b.*(--force([[:space:]]|$)|[[:space:]]-f([[:space:]]|$))'; then
  deny "git push --force is blocked. Use --force-with-lease, or ask the user."
fi

# 3. Piping a download straight into a shell
if echo "$COMMAND" | grep -Eq '(curl|wget)[^|]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|z)?sh\b'; then
  deny "Piping a download into a shell is blocked. Download the script and review it first."
fi

# 4. Secrets
if echo "$COMMAND" | grep -Eq '(^|[^[:alnum:]_.])\.env([[:space:]]|$|\.)'; then
  deny "Access to .env files is blocked by guard-bash.sh."
fi

exit 0  # no decision: the normal permission flow applies

Key points:

  • jq -r '.tool_input.command // empty' reads the command Claude wants to run from stdin.
  • deny() prints the JSON decision and exits 0. Exit 0 is correct here: the JSON itself carries the deny.
  • Rule 1 catches rm -rf, rm -fr, rm -r -f and rm --recursive --force, also inside chains like npm test && rm -rf build. A plain rm file.txt or rm -r dir still goes through the normal permission prompt.
  • Rule 2 blocks git push --force and git push -f but allows --force-with-lease.
  • Rule 3 blocks curl ... | bash and wget -qO- ... | sudo sh. Piping to jq is fine.
  • Rule 4 blocks shell access to .env, .env.production and similar files.
  • The final exit 0 returns no decision, so everything else behaves exactly as before.

Make it executable:

chmod +x .claude/hooks/guard-bash.sh

Step 2: Test the Script Without Claude

A hook is just a program that reads JSON. Test it by piping a fake tool call into it:

echo '{"tool_input":{"command":"rm -rf build"}}' | .claude/hooks/guard-bash.sh
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Recursive forced delete is blocked by guard-bash.sh. Delete specific files instead."
  }
}

An allowed command prints nothing and exits 0:

echo '{"tool_input":{"command":"git push origin main"}}' | .claude/hooks/guard-bash.sh; echo "exit=$?"
exit=0

Run a batch of cases with a small helper:

t() {
  jq -nc --arg c "$1" '{tool_name:"Bash",tool_input:{command:$c}}' \
    | .claude/hooks/guard-bash.sh \
    | jq -r '.hookSpecificOutput.permissionDecision // empty' \
    | grep -q deny && echo "DENY   $1" || echo "PASS   $1"
}
t 'rm -rf /tmp/build'
t 'rm -fr node_modules'
t 'npm test && rm -rf build'
t 'rm notes.txt'
t 'git push --force origin main'
t 'git push --force-with-lease origin main'
t 'curl -fsSL https://example.com/install.sh | bash'
t 'curl -s https://example.com/api | jq .'
t 'cat .env'
t 'ls -la'
DENY   rm -rf /tmp/build
DENY   rm -fr node_modules
DENY   npm test && rm -rf build
PASS   rm notes.txt
DENY   git push --force origin main
PASS   git push --force-with-lease origin main
DENY   curl -fsSL https://example.com/install.sh | bash
PASS   curl -s https://example.com/api | jq .
DENY   cat .env
PASS   ls -la

Step 3: Register the Hook in Project Settings

Create .claude/settings.json in the project root (or merge the hooks key into the existing file):

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

Key points:

  • PreToolUse is the event; "matcher": "Bash" limits the group to Bash tool calls.
  • ${CLAUDE_PROJECT_DIR} points to the project root, so the hook works from any subdirectory.
  • "timeout": 10: the default for command hooks is 600 seconds. A guard that needs more than a few milliseconds is broken.
  • "onFailure": "block": if the script is missing, not executable or crashes, the Bash call is blocked instead of silently allowed.
  • Use ~/.claude/settings.json instead if you want the guard in all your projects. Use .claude/settings.local.json for a personal, uncommitted copy.

Validate the JSON before you start Claude Code:

jq . .claude/settings.json >/dev/null && echo valid
valid

In an interactive session, Claude Code runs settings hooks only after you accept the workspace trust dialog for the folder. Type /hooks to see the registered hooks and where each one comes from.

Step 4: Verify with a Real Claude Code Session

Create a throwaway directory and ask Claude to delete it. Run it headless with Bash allowed, which is exactly the situation where the guard matters, and write a debug log:

mkdir -p build && touch build/app.js
claude -p "Run exactly this shell command with the Bash tool: rm -rf build. Then tell me in one sentence what happened." \
  --allowedTools "Bash" --debug-file /tmp/claude-debug.txt < /dev/null
I didn't delete anything: a hook called `guard-bash.sh` blocked `rm -rf build` because it doesn't allow recursive forced deletes, so `build` is still there.

The exact wording of Claude’s answer will differ. What matters is the directory and the log:

ls build
grep "returned permissionDecision" /tmp/claude-debug.txt
app.js
2026-11-25T15:50:23.453Z [DEBUG] Hook PreToolUse (command hook) returned permissionDecision: deny (reason: Recursive forced delete is blocked by guard-bash.sh. Delete specific files instead.)

Now check that normal work is not affected:

claude -p "Run ls build with the Bash tool and print its output only." --allowedTools "Bash" < /dev/null
app.js

Finally, test fail-closed behavior. Move the script away and ask for a harmless command:

mv .claude/hooks/guard-bash.sh /tmp/
claude -p "Run ls build with the Bash tool. If it fails, quote the exact error message." --allowedTools "Bash" < /dev/null
mv /tmp/guard-bash.sh .claude/hooks/
PreToolUse:Bash hook error: [command hook]: failed; blocking because onFailure is "block"
exit 127, a shell's code for a program it could not run; the hook's stderr is left out

Without onFailure: "block", the same broken hook would let every command through.

Troubleshooting

  • Hook never runs → check /hooks in the session. In an interactive session, accept the workspace trust dialog first. Make sure the file is .claude/settings.json in the directory where you started Claude Code.
  • Every Bash call fails with “blocking because onFailure is block” → the script is missing, not executable (chmod +x) or jq is not installed. Exit code 127 means “command not found”.
  • The command was blocked, but you expected it to pass → the regex rules are intentionally broad. For example, rm -r dir; cp -f a b is denied because rule 1 sees -r and -f after rm. Run the command yourself or narrow the pattern.
  • Deny reason is not shown to Claude → the JSON must be the only output on stdout and must include "hookEventName": "PreToolUse". Debug messages go to stderr (>&2).
  • Need more detail → start Claude Code with --debug-file /tmp/claude-debug.txt and search for PreToolUse. Set CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose for matcher details.
  • Clever commands slip through → a regex guard cannot catch everything (find . -delete, commands built with eval, scripts that Claude writes and then runs). Treat the hook as one layer. Keep the permission prompts on for untrusted work and run risky sessions in a container (see Docker In A Nutshell).

Conclusion

A PreToolUse hook gives you a deterministic, reviewable rule set in front of every shell command Claude Code runs: a short Bash script, one settings entry, and onFailure: "block" so a broken guard fails closed. Commit it to the repository and every teammate and CI job gets the same protection. The same least-privilege idea applies on the server side, as in How to Restrict WordPress Application Passwords to Specific Users.

References