AI Hooks in Claude Code: Automate What Happens Before and After Every Command

Claude Code hooks let you run your own commands before and after the agent does its work. This guide shows how to use them for formatting, logging, guardrails and the kind of automation that actually helps.

Filed under

,

Published

Written by

Last updated

Claude Code hooks let you run your own shell commands at defined points in Claude’s lifecycle. That means you can auto-format, run linters, log every change, or block risky commands entirely — without changing how you work. It’s the missing layer between “Claude did something” and “your project reacted properly.” Once you start using hooks, it’s hard to imagine going back.

TL;DR — AI Hooks in Claude Code

  • Hooks are shell commands registered in ~/.claude/settings.json under a "hooks" key
  • Key events include PreToolUse, PostToolUse, Stop (response complete) and SubagentStop; the lifecycle includes many others
  • Claude passes JSON context on stdin to your script — read it, react to it
  • Exit 0 = success; exit 2 = event-specific blocking error; other nonzero statuses generally report nonblocking errors
  • Use hooks to auto-format, run tests, log commands, or block dangerous operations
Hook EventWhen It FiresUse Case
PreToolUseBefore any tool callBlock dangerous commands, log actions
PostToolUseAfter a successful tool callAuto-format, run tests, update docs
StopWhen Claude finishes a taskSend a completion notification
SubagentStopWhen a subagent finishesCheckpoint saves, branch creation

New to hooks? Start with Writing Your First Hook below — the other sections make more sense once you’ve seen a working example.

What Claude Code Hooks Are

Hooks are shell commands you register in ~/.claude/settings.json (global) or .claude/settings.json in your project directory (scoped). They live under a top-level "hooks" key, organised by event name.

When a hook event fires, Claude Code runs your command and passes context as JSON on stdin. Your script reads that context, does whatever it needs to do, and signals back via its exit code. Think of it as middleware for Claude’s actions — the same pattern that makes Express.js middleware and Git hooks so powerful, now applied to every tool call Claude makes.

Hooks can target tools with a matcher regex and combine user and project configuration. Command hooks are shell commands, but the current product also supports other handler types. This tutorial concentrates on command hooks. Do not assume separate matching hooks execute in a defined sequence.

Four Useful Hook Events

These four events are useful starting points, not the complete lifecycle. The current hooks reference also covers events such as SessionStart, UserPromptSubmit and PostToolUseFailure.

PreToolUse fires before Claude calls any tool — before it writes a file, runs a bash command, or reads something. This is where you can intercept and block. If your PreToolUse hook exits with code 2, it blocks the tool call. Claude receives a message that the action was blocked, and can decide how to respond. This is the right hook for safety guardrails.

PostToolUse fires after a tool call succeeds. The context includes what tool was called and what it did. This is the hook for reactive automation — run your formatter after Claude writes a file, kick off your test suite after it edits code, or update a log after every bash command. An exit-2 error can give Claude feedback, but cannot undo a tool operation that already happened.

Stop fires when Claude finishes responding, not when the entire session terminates. It is useful for completion notifications. If a Stop hook asks Claude to continue, account for stop_hook_active so that the hook does not create a repeated stop-and-continue loop. Keep commits, pushes and external messages under explicit workflow control.

SubagentStop fires when a dispatched subagent finishes. If you’re using Claude Code in multi-agent mode (where Claude spawns subagents to handle parallel tasks), each subagent completion triggers this event independently. Good for checkpoints: save state, create a branch, or run partial validation between subagent runs.

Writing Your First Hook

Let’s add a PostToolUse hook that runs npm run lint every time Claude writes or edits a file. Use a project that defines an npm lint script. Merge the following into its .claude/settings.json, preserving any existing settings. The optional Stop script must exist before enabling that entry:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [{"type": "command", "command": "npm run lint --silent"}]
      }
    ],
    "Stop": [
      {
        "hooks": [{"type": "command", "command": "/home/user/.claude/hooks/on-stop.sh"}]
      }
    ]
  }
}

Here’s what each part does:

  • "PostToolUse" — the event to hook into
  • "matcher": "Write|Edit" — only fire when Claude calls the Write or Edit tool (regex match against tool name)
  • "type": "command" — run a shell command
  • "command": "npm run lint --silent" — the actual command; runs in the project’s working directory
  • The Stop hook shows how to point to an external script — useful when your hook logic gets complex

Check /hooks to confirm the effective entry. After an external settings edit, start a fresh session or follow the reload/review prompt shown by your version. Then verify a harmless edit actually triggers the linter.

Real-World Hook Recipes

Here are five patterns to adapt to your project. Validate commands independently first; the snippets below are not evidence that your linter, test suite or desktop notification service works.

1. Auto-run tests after file edits

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [{"type": "command", "command": "npm test --silent"}]
      }
    ]
  }
}

2. Record Bash event metadata without logging secrets

#!/bin/bash
# Record event metadata, not command arguments or credentials.
umask 077
python3 -c 'import json,sys,datetime; d=json.load(sys.stdin); print(json.dumps({"time":datetime.datetime.now(datetime.timezone.utc).isoformat(),"event":d.get("hook_event_name"),"tool":d.get("tool_name")}))' >> "$CLAUDE_PROJECT_DIR/.claude-hook-events.jsonl"

Register it with: "matcher": "Bash", "command": "~/.claude/hooks/audit-bash.sh" under PostToolUse.

3. Add a narrow destructive-command guard

#!/bin/bash
INPUT=$(cat)
if echo "$INPUT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('tool_input',{}).get('command',''))" | grep -q "rm -rf"; then
  echo "Blocked: rm -rf is not allowed via Claude hooks" >&2
  exit 2
fi
exit 0

Register under PreToolUse with a Bash matcher. Exit 2 blocks that call. This substring check is only an illustrative guard: shell syntax and other tools can bypass it. It is not a complete security boundary.

4. Desktop notification when Claude finishes

#!/bin/bash
# ~/.claude/hooks/on-stop.sh
notify-send "Claude Code" "Task complete" --icon=dialog-information 2>/dev/null ||
osascript -e 'display notification "Task complete" with title "Claude Code"' 2>/dev/null
exit 0

Register under Stop (no matcher needed — Stop has no tool context). Requires a working Linux desktop notification service or macOS osascript; a headless server or WSL terminal may not display anything.

5. Report pending work when Claude stops

#!/bin/bash
cd "$CLAUDE_PROJECT_DIR" || exit 1
git status --short >&2
exit 0

Advanced Patterns

Chaining hooks. Multiple matching hooks can run in parallel; do not rely on their ordering. Put dependent steps inside one script and propagate failures deliberately. A PreToolUse hook can block with exit 2; independent log writers should avoid corrupting a shared output file.

Environment variables in hooks. Claude Code exposes a few useful variables to hook scripts: CLAUDE_PROJECT_DIR points to the root of the current project, and the JSON stdin field session_id identifies the current session. Use these to make hooks that behave differently per project without hardcoding paths.

Debugging hooks. If a hook isn’t firing or isn’t doing what you expect, use the documented debug option when starting Claude Code:

claude --debug=hooks

This enables verbose output including hook execution, which command ran, and what exit code it returned. Worth pairing with stderr output in your hook scripts for fast debugging cycles.

Project vs global hooks. Global hooks in ~/.claude/settings.json apply everywhere. Project hooks in .claude/settings.json apply only in that directory. Project hooks layer on top of global ones — they don’t replace them. This lets you keep a global audit hook running everywhere while adding project-specific formatters only where they make sense.

Frequently Asked Questions

What are Claude Code hooks?

Shell commands that fire automatically before or after Claude Code performs an action, configured in ~/.claude/settings.json or a project's .claude/settings.json file.

Can hooks stop Claude from running commands?

Yes. A PreToolUse hook that exits with code 2 will block the tool call. Claude receives the block and can explain what happened.

Where are Claude Code hook settings stored?

In ~/.claude/settings.json globally, or in .claude/settings.json within a project directory for project-specific hooks.

Do hooks slow Claude Code down?
Hooks add their own execution cost. Measure the relevant command; a full test suite after every matching tool call can be expensive. Hooks are not triggered by every keystroke. Use event and tool matchers selectively.

Can I pass data back to Claude from a hook?
Yes. Command hooks can return event-specific structured JSON on stdout with exit 0. Keep stdout to that JSON object and send diagnostics to stderr. Exit 2 has event-specific error/blocking behaviour; it is not a universal warning code. Check the event’s documented output schema.

For the complement to hooks — reusable instruction sets that load when you need them — the Claude Code Skills post covers building and using skills in depth. Hooks and skills can shape the workflow, but they do not replace permission controls, isolation or review.

Hook not firing? Use the sentinel-based troubleshooting guide to separate discovery, matching, execution and output failures. Its direct fixture checks do not substitute for testing your own hook dispatch.

Related reading

Did this solve it?

Leave a Reply

Your email address will not be published. Required fields are marked *

Find more on the site

Keep reading by topic.

If this post was useful, the fastest way to keep going is to pick the topic you work in most often.

Want another useful post?

Browse the latest posts, or support TurboGeek if the site saves you time regularly.