Automate Checks with Claude Code Hooks
- 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
PreToolUsehook. - Debug a hook that doesn’t fire, and explain the security rules.
Concepts to know first
Section titled “Concepts to know first”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.”
Events (official hooks guide, 2026-10-31)
Section titled “Events (official hooks guide, 2026-10-31)”| 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.
Hook types
Section titled “Hook types”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).
Where to put them
Section titled “Where to put them”| 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 |
Step-by-step guide
Section titled “Step-by-step guide”-
Add your first hook: a notification
Open
~/.claude/settings.json(create it if needed) and add aNotificationhook. This macOS example usesosascript; 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
hookskey, addNotificationnext to the existing event keys instead of replacing the object. Then type/hooksin Claude Code: the hook should appear underNotification. To test it, switch to manual permission mode withShift+Tab, ask for something that needs permission, and switch to another window. -
Auto-format after every edit
Add this to
.claude/settings.jsonin your project. It runs Prettier on the file after theEditorWritetool succeeds.jqpulls 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 promptIn 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
matcheris case-sensitive andEdit|Writemeans “either tool.” It does not catch edits made through aBashcommand; the guide suggests aFileChangedhook if you need that. -
Block protected files
Create
.claude/hooks/protect-files.sh(from the official guide):protect-files.sh #!/bin/bashINPUT=$(cat)FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')# Normalize Windows backslash separators so the patterns below matchFILE_PATH="${FILE_PATH//\\//}"PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")for pattern in "${PROTECTED_PATTERNS[@]}"; doif [[ "$FILE_PATH" == *"$pattern"* ]]; thenecho "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2exit 2fidoneexit 0Make 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 theBlocked:message goes to Claude as feedback so it can change course. -
Block risky shell commands
This follows the guide’s
PreToolUsepattern for theBashtool, wheretool_input.commandholds the command. Save as.claude/hooks/block-risky.sh:#!/bin/bashINPUT=$(cat)COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')if echo "$COMMAND" | grep -Eq 'rm -rf|git push --force'; thenecho "Blocked: risky command: $COMMAND" >&2 # stderr becomes Claude's feedbackexit 2 # exit 2 = blockfiexit 0 # no objection; normal permission flow appliesRegister it with
"matcher": "Bash"underPreToolUse, the same way as step 3. We tested this script’s logic locally by piping sample JSON into it:rm -rf buildexited 2 with the message, andlsexited 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. -
Check what happened
When a hook seems to do nothing - Claude Code promptType /hooks→ Confirm the hook is listed under the right event
- Your settings fileCheck the matcher spelling and case, e.g. Edit|Write→ Matchers are case-sensitive and match tool names exactly
- Claude CodePress Ctrl+O for the transcript view→ A blocking message or a "hook error" notice shows what happened
- 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.
Quick reference
Section titled “Quick reference”| 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.
Common sticking points
Section titled “Common sticking points”The hook never fires
Section titled “The hook never fires”- 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 +xit on macOS and Linux.
My JSON output has no effect
Section titled “My JSON output has no effect”- 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
Stophook that blocks every time. Claude Code overrides it after eight consecutive blocks. - Fix: Read
stop_hook_activefrom the input and exit 0 when it istrue.
Practical tips
Section titled “Practical tips”- 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
PreToolUsehooks 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.
Next tutorials
Section titled “Next tutorials”- C14. Claude Code key features — CLAUDE.md, subagents, MCP, permission modes
- 1. Getting started with Claude Code
- 8. Handing off work to cloud sessions
- Dev 7. Headless and GitHub Actions —
-pruns, where the trust caution matters most - Developer guide
Sources
Last verified: Nov 16, 2026
- Automate actions with hooks (hooks guide) code.claude.com
- Hooks reference code.claude.com
Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.
Finished this tutorial?
Progress is saved only in this browser and never sent anywhere.