Get the free coreGet core

Claude Code hooks for safety: block risky commands before they run

Updated 6 min readSection 01 / Agent permissions
SHORT ANSWER

Claude Code hooks are scripts of your own that Claude Code runs at set moments in a session. A PreToolUse hook runs before a tool call and can block it. If it exits with code 2, Claude Code stops the action, and that holds even when you start with --dangerously-skip-permissions. A hook is one guard, not a wall: Claude can still change protected files with shell commands.

01How a hook talks to Claude Code

A hook is a script. Claude Code starts it when an event happens, hands it data, and reads what comes back. Claude Code hooks need no special language; shell is enough. Hooks give deterministic control: certain actions always happen, rather than relying on the model to choose to run them. Four words explain the whole mechanism.

02The events

Each hook attaches to an event. These six come up most often:

EventWhen it fires
PreToolUseBefore a tool call executes. Can block it
PostToolUseAfter a tool call succeeds. The tool has already run, so it cannot undo anything
PermissionRequestWhen a tool call needs a permission decision
SessionStartWhen a session begins or resumes
StopWhen Claude finishes responding
NotificationWhen Claude Code sends a notification

For blocking, PreToolUse is the event to use.

03Example: protect files with a script

One official example from Anthropic's hooks guide blocks edits to .env, package-lock.json and .git/. The script reads its input with jq, a command line tool for JSON, so jq must be installed. Save it as .claude/hooks/protect-files.sh:

#!/bin/bash
# protect-files.sh

INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Normalize Windows backslash separators so the patterns below match
FILE_PATH="${FILE_PATH//\\//}"

PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0

Read it top to bottom: it takes the file path from stdin, compares it with three patterns, and on a match writes a message to stderr and exits 2. If nothing matches, it exits 0 and the edit goes ahead.

Scripts must be executable for Claude Code to run them:

chmod +x .claude/hooks/protect-files.sh

Then register it in .claude/settings.json as a PreToolUse hook with the matcher Edit|Write:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

Test it. Ask Claude to add a comment to your .env file. Claude Code blocks the edit before it runs and passes the script's Blocked: message to Claude as feedback. If nothing is blocked, check the path first, because a mistyped path in settings.json means it never runs.

04Example: log every command and guard rm -rf

You can attach several to the same matcher. This official example registers two PreToolUse entries on Bash: the first appends every command to ~/.claude/bash.log, and the second runs a script that blocks rm -rf:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r .tool_input.command >> ~/.claude/bash.log"
          },
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm-rf.sh"
          }
        ]
      }
    ]
  }
}

The block-rm-rf.sh guard works like protect-files.sh above, but it reads .tool_input.command instead of the file path and exits 2 when the command contains rm -rf.

Here is a version of that script, built the same way as protect-files.sh. Save it as .claude/hooks/block-rm-rf.sh and make it executable with chmod +x:

#!/bin/bash
# block-rm-rf.sh — adapted from the official protect-files.sh example

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

if [[ "$COMMAND" == *"rm -rf"* ]]; then
  echo "Blocked: this command contains rm -rf: $COMMAND" >&2
  exit 2
fi

exit 0

It catches the exact text rm -rf. A delete written another way, such as rm -r -f, passes, so keep it as one guard among several.

The deny takes precedence, so Claude Code blocks the command and shows Claude the guardrail's stderr. The log entry is still written because the logging hook already ran. When several hooks disagree, the most restrictive answer applies, in the order deny, defer, ask, allow.

05Example: answer with JSON instead of an exit code

A script can also return a structured decision: instead of exit 2, it exits 0 and prints a JSON object to stdout. Pick one approach per hook. With deny, Claude Code cancels the tool call and feeds the reason back to Claude:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Use rg instead of grep for better performance"
  }
}

The reverse does not hold. If a hook returns allow, deny and ask rules, including enterprise managed deny lists, still apply.

06A quiet one: a macOS notification

Not every one has to block. A Notification hook can ping you when Claude needs attention. On macOS it goes into ~/.claude/settings.json like this:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

07Why Claude Code hooks still work with the flag on

PreToolUse hooks fire before any permission-mode check, in every mode, so users cannot bypass them by changing the mode. A hook that exits 2 stops the call before permission rules are even evaluated, even when an allow rule matches. That makes it a useful guard on top of the bypass flag. It does not make the flag safe on your main Mac: the docs say to use that mode only in isolated environments like containers or VMs without internet access. See dangerously skip permissions for the flag, and Claude Code permissions for the modes.

08Where hooks stop

Hooks run with your full user permissions. A hook copied from a repository you do not trust is code you did not write, so review and test it first. Cursor has its own hooks with their own rules; see Cursor YOLO mode. Git hooks, which Git runs at commit time, are a separate thing and not covered here.

09Claude Code hooks as one layer

Use them next to deny rules and a sandbox, not instead of them. The sandbox page is Claude Code sandbox; the other agent settings are in AI agent permissions, auto mode and Claude Code YOLO mode.

A hook sees only the tool calls Claude makes. Artificial Immunity's free, open-source core watches the Mac around them: Claude Code, MCP servers, git hooks, package scripts and every program start, and reports what it finds without blocking anything.

FAQ

What are Claude Code hooks?

Hooks are user-defined shell commands, HTTP endpoints, MCP tool calls, LLM prompts or subagents that run automatically at specific points in Claude Code's lifecycle. For safety, the useful kind is a shell script.

Can a hook block a command?

Yes. A PreToolUse hook runs before a tool call and can block it. If the hook exits with code 2, Claude Code stops the action.

Do hooks work with --dangerously-skip-permissions?

Yes. A hook that returns permissionDecision deny blocks the tool even in bypassPermissions mode or with the flag. The flag itself is meant only for isolated environments.

Why does my hook not block anything?

Three common causes. Exit code 1 is a non-blocking error, so use 2. A hook that timed out does not block the call. And a mistyped path in settings.json means the hook never runs.

Where do I put hooks?

In ~/.claude/settings.json for all your projects on this machine, or in .claude/settings.json inside a project, which can be committed to the repo.

Are hooks safe to copy from GitHub?

Not blindly. Command hooks run with your full user permissions. Review and test every hook command before you add it.

Sources

  1. Claude Code docs: hooks reference
  2. Claude Code docs: hooks guide
  3. Claude Code docs: permissions
  4. Claude Code docs: permission modes
  5. Artificial Immunity
Using hooks as a last line of defense? Artificial Immunity watches the Mac where your agents work.Get the free core