All posts

· Updated · By

Claude Code Hooks for Automation (Part 5)

claude-codeautomationhooks

When I first discovered Claude Code hooks, I thought I’d found a cheat code for developer productivity. No more manual validation steps. No more forgetting security checks before deployment. No more scrambling to keep my team updated on task completion.

Hooks are the automation layer that transforms Claude Code from a powerful tool into an autonomous system that works while you’re focused on the actual problem-solving.

What Are Hooks?

Hooks are user-defined handlers, usually shell commands, that execute automatically when specific actions happen during a Claude Code session. Think of them as Git hooks or webhook handlers, but for your AI-assisted development workflow.

Instead of manually running checks or notifications, you define once what should happen when Claude edits a file, uses a tool, or completes a task. Then it just… happens. Automatically. Every time.

The key difference from instructions in CLAUDE.md: an instruction is a request the model can forget, while a hook is code that always runs.

For an indie developer managing multiple projects, this eliminates entire categories of human error. You can’t forget to lint if the linting happens automatically after every file change.

The Hook Events You Will Actually Use

Claude Code fires hook events at three cadences: once per session (SessionStart, SessionEnd), once per turn (UserPromptSubmit, Stop), and on every tool call inside the agent loop (PreToolUse, PostToolUse). There are more than thirty events in total; the official hooks reference lists all of them. These are the ones I reach for:

EventWhen it firesCan it block?
PreToolUseBefore a tool call runsYes: exit 2 blocks the call
PostToolUseAfter a tool call succeedsNo: exit 2 shows stderr to Claude
UserPromptSubmitWhen you send a prompt, before Claude sees itYes: exit 2 rejects the prompt
StopWhen Claude finishes respondingYes: exit 2 makes Claude keep working
SessionStartWhen a session begins or resumesNo
NotificationWhen Claude Code needs your attentionNo
TaskCompletedWhen a task is being marked completeYes: exit 2 keeps the task open
FileChangedWhen a watched file changes on diskNo

PreToolUse is the guard rail. Use it to stop dangerous shell commands or edits to files Claude should never touch.

PostToolUse is for side effects: formatting a file Claude just wrote, running a linter, or logging.

UserPromptSubmit can add context to a prompt or reject one that contains something it shouldn’t, such as a pasted secret.

Stop is where I put “are the tests green?” checks. If the check fails, exiting 2 sends Claude back to work.

How Hooks Are Configured

Hooks live in your settings JSON, not in a special hooks folder. Where you put them sets their scope:

FileScope
~/.claude/settings.jsonAll your projects
.claude/settings.jsonThis project, committed to the repo
.claude/settings.local.jsonThis project, just for you

The config has three levels: the event, a matcher group that filters when it fires, and one or more handlers that run:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format.sh" }
        ]
      }
    ]
  }
}

Two details trip people up:

  • Input arrives as JSON on stdin, not as positional arguments. A PostToolUse hook for an edit receives tool_name, tool_input (including tool_input.file_path), and tool_response. Parse it with jq.
  • Exit code 2 is the blocking code, not 1. Exit 0 means success; exit 2 blocks the action on events that can block, and Claude sees your stderr as the reason; any other code is a non-blocking error that lets the action go ahead.

You can also type /hooks inside a session to see and manage what is configured.

Practical Examples

All the scripts below use jq to read the JSON input. Save them under .claude/hooks/ and make them executable with chmod +x.

Example 1: Auto-Format After Every Edit

#!/bin/bash
# .claude/hooks/format.sh  (PostToolUse, matcher "Edit|Write")
FILE=$(jq -r '.tool_input.file_path // empty')

case "$FILE" in
  *.ts|*.tsx|*.js|*.jsx) npx --no-install prettier --write "$FILE" >/dev/null 2>&1 ;;
  *.swift) command -v swiftformat >/dev/null && swiftformat "$FILE" >/dev/null 2>&1 ;;
esac
exit 0

Every file Claude writes comes out formatted, and the hook never blocks anything because it always exits 0.

Example 2: Block Destructive Shell Commands

#!/bin/bash
# .claude/hooks/block-rm.sh  (PreToolUse, matcher "Bash")
COMMAND=$(jq -r '.tool_input.command // empty')

if echo "$COMMAND" | grep -qE 'rm -rf|git push --force'; then
  echo "Blocked by hook: destructive command. Ask the user first." >&2
  exit 2
fi
exit 0
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh" }]
      }
    ]
  }
}

Because the hook exits 2, the tool call is cancelled and Claude reads the stderr message, so it can choose a safer approach.

Example 3: Don’t Let Claude Stop While Tests Fail

#!/bin/bash
# .claude/hooks/tests-green.sh  (Stop, no matcher)
INPUT=$(cat)
# Avoid an infinite loop: if we already sent Claude back once, let it stop.
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then exit 0; fi

if ! npm test --silent >/tmp/test-output.txt 2>&1; then
  echo "Tests are failing. Fix them before finishing:" >&2
  tail -n 30 /tmp/test-output.txt >&2
  exit 2
fi
exit 0

Example 4: Catch Secrets in Prompts

#!/bin/bash
# .claude/hooks/no-secrets.sh  (UserPromptSubmit)
PROMPT=$(jq -r '.prompt')

if echo "$PROMPT" | grep -qE 'sk-ant-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16}'; then
  echo "Prompt looks like it contains an API key. Remove it and resend." >&2
  exit 2
fi
exit 0

Match on real key formats rather than words like “password” or “token”, or the hook will reject half your prompts.

Example 5: Ping Slack When a Task Completes

#!/bin/bash
# .claude/hooks/notify.sh  (TaskCompleted)
[ -z "$SLACK_WEBHOOK_URL" ] && exit 0
SUBJECT=$(jq -r '.task_subject')
curl -s -X POST "$SLACK_WEBHOOK_URL" -H 'Content-type: application/json' \
  --data "$(jq -n --arg t "Claude finished: $SUBJECT" '{text: $t}')" >/dev/null
exit 0

Narrowing When Hooks Run

The matcher is a string, not an object. For tool events it matches the tool name:

  • "Bash" matches only the Bash tool.
  • "Edit|Write" matches either tool.
  • "mcp__github__.*" (anything with regex characters) is a regular expression, here every tool from the github MCP server.

For finer control, add an if field to a handler. It uses permission-rule syntax against the tool name and arguments, so the script only spawns when it matters:

{
  "matcher": "Bash",
  "hooks": [
    { "type": "command", "if": "Bash(git commit*)", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/pre-commit.sh" }
  ]
}

Best Practices for Reliable Hooks

Keep hooks fast. Every PreToolUse and PostToolUse hook runs on every matching tool call. Anything slow belongs in a Stop hook or a background job.

Use exit 2 on purpose. It is the only exit code that blocks. Exit 1 is a non-blocking error: the action still goes ahead.

Write blocking reasons for Claude. On a block, stderr is what Claude reads. “Blocked: run the tests first” gets a better next step than “error”.

Guard Stop hooks against loops. Check stop_hook_active so a failing check can’t keep Claude running forever.

Reference scripts with $CLAUDE_PROJECT_DIR. Hooks run in the current working directory, which changes when Claude runs cd. Absolute paths through the variable keep working.

Test with real input. Pipe a sample JSON payload into the script before wiring it up: echo '{"tool_input":{"command":"rm -rf /"}}' | .claude/hooks/block-rm.sh; echo $?.

What’s Next?

Hooks are the foundation of Claude Code automation, but they’re just the beginning. In Part 6, we cover plan mode, checkpoints, plugins, and running Claude Code headless in scripts and CI.

For now, start with one simple hook. Auto-format your code. Run a security check before commits. Send yourself a Slack notification when long tasks complete. These small automations compound into massive time savings over a week of development.

That’s the real power of Claude Code hooks — they turn repetitive manual tasks into invisible automation that just works.

Frequently asked questions

What are Claude Code hooks?

Hooks are user-defined handlers, usually shell commands, that Claude Code runs automatically at specific points such as before a tool call (PreToolUse), after it (PostToolUse), when you submit a prompt, or when Claude stops. Unlike CLAUDE.md instructions, they always run.

Where do I configure Claude Code hooks?

In a settings file under a hooks key: ~/.claude/settings.json for all projects, .claude/settings.json to share with the repo, or .claude/settings.local.json for just you. Each event lists matcher groups, and each group lists handlers such as {"type": "command", "command": "..."}.

How does a hook block an action?

Exit with code 2. On blocking events such as PreToolUse, UserPromptSubmit, and Stop, the action is stopped and Claude reads your stderr as the reason. Exit 0 continues, and any other exit code, including 1, is a non-blocking error.

How does a hook know which file or command is involved?

Claude Code sends a JSON payload on stdin. Tool events include tool_name and tool_input, for example tool_input.file_path for edits or tool_input.command for Bash. Read it with jq.

More from the studio.

The apps this workflow ships live on the ZenoLab apps page, with every release in the shiplog.