Skip to content
한국어

Automate Checks with Claude Code Hooks

In short
  • A hook is a shell command (or HTTP call, prompt, agent) that Claude Code runs automatically at a point in its lifecycle. Unlike CLAUDE.md, it is deterministic: it happens every time, instead of relying on the model to remember.
  • Typical uses: format after edits (PostToolUse), block risky commands or protected files (PreToolUse), and notify you when Claude waits for input (Notification).
  • A hook gets event data as JSON on stdin. Exit 0 means no objection, exit 2 blocks the action and sends your stderr message to Claude as feedback.
  • Hooks live in settings files: ~/.claude/settings.json (all projects), .claude/settings.json (shared with the repo), .claude/settings.local.json (just you).
  • Command hooks run with your full user permissions. Read and test every command before you add it, especially hooks that came with someone else’s repo.
  • We checked the official docs on 2026-10-31. We tested only the blocking script’s logic locally with sample JSON; we did not run Claude Code itself.

What you’ll be able to do after this tutorial

Section titled “What you’ll be able to do after this tutorial”
  • Add a hook to a settings file and confirm it with /hooks.
  • Auto-format every file Claude edits.
  • Block dangerous commands and edits to protected files with a PreToolUse hook.
  • Debug a hook that doesn’t fire, and explain the security rules.

C14 introduced hooks in one step. This tutorial goes deeper. The key idea: CLAUDE.md is context that Claude usually follows, while a hook is code that always runs. Use hooks for “must always happen” and “must never happen.”

Event When it fires
SessionStart / SessionEnd A session begins or resumes / ends
UserPromptSubmit A prompt is submitted, before Claude processes it
PreToolUse Before a tool call runs. Can block it
PermissionRequest A tool call needs a permission decision
PostToolUse / PostToolUseFailure After a tool call succeeds / fails
Notification Claude Code sends a notification
SubagentStart / SubagentStop A subagent starts / finishes
Stop Claude finishes responding (not on user interrupts)
PreCompact / PostCompact Around context compaction
FileChanged, CwdChanged, ConfigChange A watched file, working directory, or config changes

The guide’s table lists more events (for example Setup, TaskCreated, WorktreeCreate, PreModelSwitch, Elicitation). See the Hooks reference for the full list and schemas.

Most hooks are "type": "command" (a shell command). The guide also lists http (POST event data to a URL), mcp_tool, prompt (a single-turn model check, for judgment calls), and agent (multi-turn verification; the guide marks agent hooks as experimental).

Location Scope Shareable
~/.claude/settings.json All your projects No
.claude/settings.json This project Yes, commit it
.claude/settings.local.json This project No (gitignored)
Managed policy settings Organization Yes, admin-controlled
Plugin hooks/hooks.json, skill or subagent frontmatter While the plugin is on / skill invoked / subagent runs Yes
0/5 done
  1. Add your first hook: a notification

    Open ~/.claude/settings.json (create it if needed) and add a Notification hook. This macOS example uses osascript; the hooks guide has Linux and Windows commands too.

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

    If the file already has a hooks key, add Notification next to the existing event keys instead of replacing the object. Then type /hooks in Claude Code: the hook should appear under Notification. To test it, switch to manual permission mode with Shift+Tab, ask for something that needs permission, and switch to another window.

  2. Auto-format after every edit

    Add this to .claude/settings.json in your project. It runs Prettier on the file after the Edit or Write tool succeeds. jq pulls the path out of the JSON on stdin.

    {
    "hooks": {
    "PostToolUse": [
    {
    "matcher": "Edit|Write",
    "hooks": [
    {
    "type": "command",
    "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
    }
    ]
    }
    ]
    }
    }
    Copy and paste this prompt

    In this project, add a line to a JavaScript file that uses single-quoted strings. Then show me the file so I can check whether it was reformatted.

    With Prettier’s default settings the hook rewrites single quotes to double quotes. On success Claude Code shows nothing in the conversation, so check the file itself. The matcher is case-sensitive and Edit|Write means “either tool.” It does not catch edits made through a Bash command; the guide suggests a FileChanged hook if you need that.

  3. Block protected files

    Create .claude/hooks/protect-files.sh (from the official guide):

    protect-files.sh
    #!/bin/bash
    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

    Make it executable on macOS and Linux, then register it:

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

    Ask Claude to add a comment to .env. The edit is blocked and the Blocked: message goes to Claude as feedback so it can change course.

  4. Block risky shell commands

    This follows the guide’s PreToolUse pattern for the Bash tool, where tool_input.command holds the command. Save as .claude/hooks/block-risky.sh:

    #!/bin/bash
    INPUT=$(cat)
    COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
    if echo "$COMMAND" | grep -Eq 'rm -rf|git push --force'; then
    echo "Blocked: risky command: $COMMAND" >&2 # stderr becomes Claude's feedback
    exit 2 # exit 2 = block
    fi
    exit 0 # no objection; normal permission flow applies

    Register it with "matcher": "Bash" under PreToolUse, the same way as step 3. We tested this script’s logic locally by piping sample JSON into it: rm -rf build exited 2 with the message, and ls exited 0. A plain pattern match like this is a simple guard, not a security boundary; it won’t catch every way to write a dangerous command.

  5. Check what happened

    When a hook seems to do nothing
    1. Claude Code promptType /hooks→ Confirm the hook is listed under the right event
    2. Your settings fileCheck the matcher spelling and case, e.g. Edit|Write→ Matchers are case-sensitive and match tool names exactly
    3. Claude CodePress Ctrl+O for the transcript view→ A blocking message or a "hook error" notice shows what happened
    4. TerminalStart with claude --debug-file /tmp/claude.log and tail -f that file→ Exit codes, stdout, and stderr are logged

    This is a simplified flow. See the official help page for the actual screens.

Exit code Meaning
0 No objection. For UserPromptSubmit and SessionStart, stdout is added to Claude’s context
2 Block (on events that can be blocked). stderr goes to Claude or the user, depending on the event
Other Non-blocking error on most events; the action proceeds

Default timeouts (guide): 10 minutes for command, http and mcp_tool hooks (30 seconds for UserPromptSubmit, PreModelSwitch, and PostModelSwitch; 10 seconds for MessageDisplay), 30 seconds for prompt hooks, 60 seconds for agent hooks. Override with timeout (seconds). Command hooks can’t call / commands or tools. PostToolUse can’t undo what the tool already did.

  • Cause: Wrong event, wrong matcher, or a typo in the tool name.
  • Fix: Run /hooks, compare with the event table, and remember matchers are case-sensitive.

The script isn’t executed or fails with “permission denied”

Section titled “The script isn’t executed or fails with “permission denied””
  • Cause: The script isn’t executable.
  • Fix: chmod +x it on macOS and Linux.
  • Cause: Shell profile output (for example from ~/.zshrc) printed before your JSON, or fields at the wrong level.
  • Fix: Keep stdout clean and put decision fields where the reference says. See the guide’s troubleshooting section.

Claude keeps working because my Stop hook blocks it

Section titled “Claude keeps working because my Stop hook blocks it”
  • Cause: A Stop hook that blocks every time. Claude Code overrides it after eight consecutive blocks.
  • Fix: Read stop_hook_active from the input and exit 0 when it is true.
  • Start with one small hook and verify it before adding more.
  • Quote shell variables ("$VAR"), use absolute script paths such as "$CLAUDE_PROJECT_DIR"/..., and skip .env, .git/, and keys, as the reference’s best practices say.
  • Don’t have two PreToolUse hooks rewrite the same tool’s input; the result isn’t guaranteed.
  • Commit shared hooks in .claude/settings.json, and tell teammates what they do.
  • Write what you need in plain words and ask Claude to draft the hook, then read it before you save it.

Sources

Last verified: Nov 16, 2026

Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.