OmniscioGuidesClaude Code hooks examples
Five Claude Code hooks examples you can copy
Anthropic’s documentation describes hooks as user-defined commands that execute automatically at specific points in Claude Code’s lifecycle. The definition is easy. The part people get wrong is which event to use and which exit code actually stops something.
These five are the setups Anthropic’s documentation and the most common questions about hooks point at: formatting an edit, blocking a dangerous command, a desktop alert, tests before a stop, and a log of every tool call.
Checked against Anthropic’s Claude Code hooks documentation on November 25, 2026. By the Omniscio team. Updated .
Copy this one first
The shortest useful hook: format every file Claude edits, using the project’s own Prettier. Put it in .claude/settings.json, keep any event keys already in that file, and install jq if you have not got it.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}Check it with /hooks, then ask Claude to add a line with single quotes to a JavaScript file and open the file: Prettier’s defaults rewrite them to double quotes. The full format-on-edit recipe explains every line, how to scope it to file types, and the five ways it fails quietly.
The shape of every hook
A hook has three levels, and knowing which one a problem is at saves most of the debugging time.
- The event — the moment:
PreToolUsebefore a tool call,PostToolUseafter a successful one,Stopwhen the agent finishes,Notificationwhen Claude Code raises an alert, and so on. - The matcher — a filter on the event. On tool events it is the tool name, written as an exact list (
Edit|Write) or, when it contains any other character, as an unanchored JavaScript regular expression. - The handler — what runs. A
commandis the common one; Anthropic also documentshttp,mcp_tool,promptand the experimentalagenttypes.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "/path/to/your-script.sh" }
]
}
]
}
}A command handler gets the event as JSON on stdin, so a hook can read the tool name, the tool’s input and the session from it. The Claude Code hooks guide lists the fields of every event; here it is enough to know that tool_name and tool_input are what most scripts read.
Before any of them works
- Pick the file. A project’s
.claude/settings.jsonis committed and shared;~/.claude/settings.jsonapplies to every project on your machine;.claude/settings.local.jsonis the one that stays out of git. - Make the script runnable. A shell script needs
chmod +xon macOS and Linux, or the hook cannot start it. A one-line command in the settings file needs nothing. - Parse the input with
jq. The examples here do, because that is the form Anthropic’s use. A hook that ignores stdin needs nothing. - Quote your variables. A hook runs with your full user permissions and a path with a space in it is the first thing that breaks; Anthropic’s security section asks for
"$VAR"everywhere. - Remember what merges. User, project, local and managed hooks add to each other rather than replacing each other, and the same handler defined in two settings files runs once.
The five recipes
1. Format every file Claude edits
A PostToolUse hook with an Edit|Write matcher that runs Prettier on the path in the event. Claude Code has no save step, so “format on save” becomes “format after the edit”. The recipe covers scoping it to file types, and the reason a working hook shows nothing at all.
2. Block rm -rf and other dangerous commands
A PreToolUse hook with a Bash|PowerShell matcher reads the command before it runs and exits 2 to stop it. This is the recipe where the exit code is the whole lesson: 2 blocks, 1 does nothing, and a hook that cannot start blocks nothing unless onFailure says so.
3. Get a desktop notification when Claude needs you
A Notification hook with the platform’s own notifier: osascript on macOS, notify-send on Linux, PowerShell on Windows. The timing is the interesting part — a permission prompt notifies after about six seconds, an idle prompt after about 60 — and the recipe pairs it with a Stop hook for the moment the turn actually ends.
4. Run the tests before Claude stops
A Stop hook runs your suite when the agent finishes and exits 2 to send Claude back to work with the failure. It is the only one here that starts a new turn, and the only one whose own block can trigger it again: stop_hook_active and an eight-continuation cap are the two facts that keep it sane.
5. Log every tool call
PreToolUse, PostToolUse and PostToolUseFailure, each appending one compact JSON line to a file. It answers the questions a transcript answers badly: what ran, in what order, how long it took, what failed. The recipe is written around the one mistake that ruins it — logging tool_input whole, which copies your source code into the log.
Between them the five use PreToolUse, PostToolUse, PostToolUseFailure, Notification and Stop — the events most hooks end up on.
The exit code that decides everything
Every recipe here depends on this table, and the table is shorter than people expect.
| What the hook did | What Claude Code does |
|---|---|
| Exits 0 | Success. Any JSON it printed is applied, and the action continues unless that JSON blocks or denies. |
Exits 2 on PreToolUse | Blocks the tool call. Your stderr becomes the reason Claude sees. |
Exits 2 on Stop | Prevents Claude from stopping and continues the conversation, with your stderr as the reason to keep working. |
Exits 2 on PostToolUse | Shows your stderr to Claude, but the tool has already run. |
Exits 2 on Notification | Ignored. The exit code and stderr are discarded. |
| Exits with anything else, including 1 | A non-blocking error. The action goes ahead and you see a <hook name> hook error notice — except on Notification, where it is silent. |
Anthropic states the trap in one sentence: exit code 1 without valid JSON output is a non-blocking error, even though 1 is the conventional Unix failure code. A hook meant to enforce a policy uses exit 2. If a hook must block when it cannot even start, onFailure: "block" does that for a command, http or mcp_tool handler, and it requires Claude Code v2.1.295 or later (v2.1.328 for mcp_tool); it has no effect on Stop, SubagentStop, TaskCompleted or TeammateIdle hooks.
Testing any hook in four steps
- Run the command by hand, with sample JSON. The input arrives on stdin, so
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | .claude/hooks/your-script.sh; echo $?tells you what the hook will decide before any session is involved. - Check it is registered.
/hooksis a read-only browser that lists each hook under its event and labels where it comes from; selecting one shows the settings file or plugin that defines it. Its All events entry browses every event even when none is configured. - Trigger it for real. A successful hook often shows nothing, though it can surface a
systemMessageor Stop hook feedback, so look for the effect: the reformatted file, the blocked call, the line in the log. - Read the debug log when it does not.
claude --debug-file /tmp/claude.logand follow it, or run/debugmid-session. The transcript view (Ctrl+O) shows a blocking error’s message on most events;ConfigChangeandElicitationshow none.
Where to go next
- Claude Code hooks is the overview: every event the documentation lists, where the configuration lives and what it merges with, the three hooks Anthropic’s quickstart gives, and the JSON output fields that go beyond exit codes.
- The PreToolUse hook error guide reads the error lines one by one, for when a hook you copied is refusing to work.
- The hooks builder assembles a settings block from the event, matcher and handler you pick, and flags fields Claude Code would ignore.
- Permission modes is the other half of blocking: a hook’s deny holds in every mode, and what else changes with the mode is there.
How this page was written
Everything about events, nesting, matchers, handler types, exit codes, timeouts and the input fields was read from Anthropic’s Claude Code hooks reference on November 25, 2026, quoted from the page as it reads today. The testing steps follow Anthropic’s own troubleshooting section.
The five were chosen from the phrases Google’s autocomplete completes for Claude Code hook queries, checked on the same day, and from the examples Anthropic’s documentation leads with. Autocomplete shows what people type, not how often, and this page does not claim a volume.
Each recipe’s script was run here with sample JSON; each recipe page says what was measured and what was taken from the documentation. None of the hooks was wired into a live Claude Code session for these pages.
Sources
- Anthropic’s Hooks reference, for the lifecycle, configuration, matcher rules, handler types, exit codes, timeouts and security, read November 25, 2026.
- Anthropic’s Automate actions with hooks, for the quickstart examples, the troubleshooting list and the permission-mode limits, read November 25, 2026.
Common questions
Where do Claude Code hooks go?
In a settings file, under a hooks object keyed by event name. A project’s .claude/settings.json can be committed so the whole team gets the hook; ~/.claude/settings.json applies to every project on your machine, and .claude/settings.local.json stays out of git. Managed policy settings, a plugin’s hooks/hooks.json, and a skill’s or subagent’s frontmatter can also carry hooks.
What is the difference between PreToolUse and PostToolUse?
PreToolUse runs after Claude builds the tool’s parameters and before the tool call is processed, so it can block it. PostToolUse runs immediately after a tool completes successfully, so it can add context but cannot undo what the tool did.
Do hooks use extra tokens?
A command hook does not call a model itself, so running it costs no model tokens. Text it returns as additional context, or plain stdout on events such as UserPromptSubmit and SessionStart, is added to Claude’s context and does cost tokens on later requests. prompt and agent hooks call a Claude model directly and cost tokens.
Can several hooks run on one event?
Yes. Each matching handler runs, and Anthropic documents that handlers for one event run in parallel. If you define the same handler in more than one settings file it runs once, while a plugin’s or skill’s copy of the same handler stays separate.
Do hooks run in subagents and cloud sessions?
Hooks from settings files, managed policy and plugins also run inside subagents. Cloud sessions do not read your local ~/.claude/settings.json, so a hook you rely on locally is not automatically there.
Write the hook once, run it in every session
Omniscio runs your Claude Code sessions side by side and composes the hooks it ships, and any you define, into every session it spawns, kept in its own database. Hooks in your project’s .claude/settings.json keep working exactly as described above; the Omniscio panel is an addition for the sessions it starts.
The features page covers what else it does, pricing covers the plans, and you can download it for Windows, macOS or Linux.