Claude Code hooks: three working examples from the docs
A hook is a shell command Claude Code runs at a fixed point, such as after every file edit or before a tool call. Unlike an instruction, it always runs. Put hooks in .claude/settings.json for one project or ~/.claude/settings.json for all; type /hooks to see what is configured.
How a hook is set up
- Shape: hooks → event name → a list of { matcher, hooks: [{ type: "command", command }] }.
- Common events: PreToolUse (before a tool runs, can block it), PostToolUse (after it ran), Stop (when Claude is about to finish), Notification, SessionStart, PreCompact.
- Input arrives as JSON on stdin. For Edit and Write the file path is tool_input.file_path; read it with jq.
- Exit code 2 blocks the action on events that allow it, and what you print to stderr goes back to Claude as feedback.
1. Format every file Claude edits
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" }
]
}
]
}
}2. Block edits to protected files
#!/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{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
]
}
]
}
}Run chmod +x .claude/hooks/protect-files.sh first. The docs point out that Claude can still change these files with shell commands, so add a permissions deny rule such as Edit(/.env) as well.
3. Get notified when Claude needs you
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{ "type": "command", "command": "notify-send 'Claude Code' 'Claude Code needs your attention'" }
]
}
]
}
}On macOS the docs use osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"' as the command. The first two examples need jq installed.
When a skill or vault helps, and when it does not
Helps
- Skills and plugins can ship hooks: a plugin's hooks/hooks.json merges with yours when the plugin is enabled, and a skill can declare hooks in its frontmatter.
- A packaged hook saves you writing and debugging the script yourself.
Does not help
- Read any hook you install before enabling it. A hook runs shell commands on your machine with your permissions.
- For a one-line formatter, writing the hook yourself is quicker than finding a package.