~/academy $ claude learn hooks
Hooks: rules Claude Code follows every time
What Claude Code hooks are, the main hook events, a formatter that runs after every edit, a guard that blocks edits to secrets, and where hooks are configured. 8 min
Watch it done: add a formatter hook and a protected-files guard
Step 1 of 7
Open a terminal in your project. These hooks read their input with jq, so install it first: brew install jq on a Mac, apt-get install jq on Debian or Ubuntu.
- Open a terminal in your project. These hooks read their input with jq, so install it first: brew install jq on a Mac, apt-get install jq on Debian or Ubuntu. Type: cd ~/projects/my-app.
- Make a hooks folder and save this guard script in it. It reads the path Claude is about to edit and exits with code 2 if the path is protected, which blocks the edit. Type: mkdir -p .claude/hooks. Create .claude/hooks/protect-files.sh containing: #!/bin/bash # protect-files.sh INPUT=$(cat) FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') # Turn Windows backslashes into slashes 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
- On macOS and Linux, make the script executable. Claude Code cannot run a hook script that is not. Type: chmod +x .claude/hooks/protect-files.sh.
- Register both hooks in the project settings. The guard runs before every Edit or Write, and Prettier formats each file straight after it is edited. Create .claude/settings.json containing: { "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" } ] } ] } }
- Start Claude Code in the project so it loads the new settings. Type: claude. First time in this folder: accept the workspace trust dialog. Hooks from settings files do not run until you do.
- Check both hooks loaded. If the list is empty, look for a JSON mistake such as a trailing comma. Type: /hooks. A read-only list of your hooks opens, with the PreToolUse and PostToolUse entries labelled as coming from project settings. Press Esc to go back.
- Test the guard. The hook decides, not the model, so the rule holds every time. Type: add a comment to the .env file. Claude Code blocks the edit before it runs and passes the Blocked: message to Claude as feedback, so it can change approach.
Script, settings and commands from the official Claude Code hooks guide and hooks reference, checked 18 November 2026. Lines marked Note describe what happens and are not real output.
$ Read
Instructions ask, hooks make sure
A hook is a shell command that Claude Code itself runs at a fixed point in a session: before a tool runs, after a file is edited, when Claude stops. The model does not decide whether it happens. That is the difference from a line in CLAUDE.md, which Claude usually follows but can forget.
Use hooks for things that must happen every time: format each edited file, block writes to secrets, notify you when Claude is waiting, log every command. Hooks can also call a URL, call an MCP tool or ask a Claude model to judge something, but plain command hooks are where to start.
Each hook receives details of the event as JSON on standard input, so your script can read the tool name, the command or the file path. The examples here use jq to read that JSON, so install it first: brew install jq on a Mac, apt-get install jq on Debian or Ubuntu.
Lesson notes: Hooks: rules Claude Code follows every time
Everything in this lesson as text, for revision or to read without the interactive steps. By the end you will be able to: You add a formatter hook and a protected-files guard to a project and check both with /hooks.
Step 1 of 7 · Read
Instructions ask, hooks make sure
A hook is a shell command that Claude Code itself runs at a fixed point in a session: before a tool runs, after a file is edited, when Claude stops. The model does not decide whether it happens. That is the difference from a line in CLAUDE.md, which Claude usually follows but can forget.
Use hooks for things that must happen every time: format each edited file, block writes to secrets, notify you when Claude is waiting, log every command. Hooks can also call a URL, call an MCP tool or ask a Claude model to judge something, but plain command hooks are where to start.
Each hook receives details of the event as JSON on standard input, so your script can read the tool name, the command or the file path. The examples here use
jqto read that JSON, so install it first:brew install jqon a Mac,apt-get install jqon Debian or Ubuntu.Step 2 of 7 · Read
The events you will actually use
Claude Code has more than 30 hook events (checked 18 November 2026). Most projects need only a few of them.
For tool events, a
matcherpicks which tools fire the hook.Edit|Writematches either tool exactly. A matcher containing other characters is treated as a regular expression, somcp__github__.*matches every tool from an MCP server named github.SessionStart A session starts or resumes
UserPromptSubmit You send a prompt, before Claude sees it (can block it)
PreToolUse Just before a tool call runs (can block it)
PostToolUse Just after a tool call succeeds
Notification Claude Code sends a notification, for example while waiting for you
Stop Claude finishes responding
PreCompact Just before the conversation is compacted
SessionEnd The session ends
Step 3 of 7 · Read
A formatter that runs after every edit
Add this to
.claude/settings.jsonin your project. After every Edit or Write, the hook pulls the file path out of the JSON and runs Prettier on that one file. When it works you see nothing in the conversation: the file is simply formatted.Where you put a hook decides who gets it:
~/.claude/settings.jsonfor all your projects,.claude/settings.jsonto commit and share with the team,.claude/settings.local.jsonfor just you in this project. Plugins, skills and subagents can carry hooks too. To switch every hook off without deleting any, set"disableAllHooks": true..claude/settings.json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" } ] } ] } }Step 4 of 7 · Read
A guard that blocks protected files, and exit code 2
This PreToolUse hook runs a script before every Edit or Write. If the target path matches a protected pattern, the script writes a reason to stderr and exits with code 2. Claude Code blocks the tool call and passes the reason to Claude, so it can change approach.
Exit codes matter. 0 means no objection, and the normal permission rules still apply: exit 0 never approves anything by itself. 2 blocks the action on events that can block. Any other code, including 1, is a non-blocking error by default: the action goes ahead and a hook error notice appears. If a hook enforces a rule, it must exit 2.
On macOS and Linux make the script executable with
chmod +x. A guard on Edit and Write does not stop Claude changing the same file through a shell command. To block the common ones, pair it with a deny rule such asEdit(/.env)underpermissions.deny..claude/hooks/protect-files.sh #!/bin/bash INPUT=$(cat) FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') FILE_PATH="${FILE_PATH//\\//}" # turn Windows backslashes into slashes PROTECTED=(".env" "package-lock.json" ".git/") for pattern in "${PROTECTED[@]}"; do if [[ "$FILE_PATH" == *"$pattern"* ]]; then echo "Blocked: $FILE_PATH is protected ($pattern)" >&2 exit 2 fi done exit 0Register it in .claude/settings.json { "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" } ] } ] } }Step 5 of 7 · Quiz
Check your understanding
Your PreToolUse script spots a forbidden command and exits with code 1. What happens?
- The tool call is blocked, because 1 means failure.
- The command still runs, and a hook error notice appears in the transcript.
- Claude Code ends the session to be safe.
- Claude Code asks you to approve the command.
Show the answer
The command still runs, and a hook error notice appears in the transcript. Any code other than 0 or 2 is a non-blocking error. Change the script to exit 2 so the block actually happens.
Step 6 of 7 · Sort
Hook or CLAUDE.md?
Does each need a guarantee (hook) or guidance (CLAUDE.md)?
- Run the formatter on every file Claude edits
- Prefer small functions and descriptive names
- Never let Claude edit the .env file
- Explain that the API lives in the services folder
- Ping your desktop whenever Claude is waiting for input
- Write commit messages in the imperative mood
Show the answers
- Run the formatter on every file Claude edits: Hook. It must happen every time, with no judgement involved. A PostToolUse hook does exactly that.
- Prefer small functions and descriptive names: CLAUDE.md. A style preference that needs judgement. Guidance belongs in CLAUDE.md.
- Never let Claude edit the .env file: Hook. A hard rule. A PreToolUse guard that exits 2, plus a deny rule, enforces it.
- Explain that the API lives in the services folder: CLAUDE.md. Background knowledge about the project, not an action to enforce.
- Ping your desktop whenever Claude is waiting for input: Hook. A Notification hook fires on that event whatever Claude is thinking.
- Write commit messages in the imperative mood: CLAUDE.md. A writing convention Claude can follow from instructions.
Step 7 of 7 · Try it in the terminal
Check your hooks loaded
Inside a Claude Code session, open the read-only browser that lists every configured hook and where it comes from. Type the command.
Hint: It is a slash command named after the feature.
Show the command
$ /hooks Hooks PreToolUse Edit|Write "$CLAUDE_PROJECT_DIR"/.claude/hooks/protect-files.sh Project settings PostToolUse Edit|Write f=$(jq -r '.tool_input.file_path') && npx prettier ... Project settings All events