Tutorial
Claude Code hooks: run checks around every tool call
Write Claude Code PreToolUse and PostToolUse hooks that block destructive shell commands, format every file Claude edits and log each command for later audit.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Instructions in CLAUDE.md are advice. Claude usually follows them, but nothing forces it to. Hooks are the part of Claude Code that does force things: shell commands (or HTTP calls, prompts or MCP tools) that run at fixed points in the agent’s lifecycle, every time, whatever the model decides.
This tutorial builds three hooks you can keep:
- A
PreToolUsehook that blocks destructive shell commands before they run. - A
PostToolUsehook that formats every file Claude edits. - A
PostToolUsehook that writes each shell command to a log you can audit later.
Everything here was checked against the Claude Code hooks reference on 20 November 2026 (Claude Code 2.1). The hooks API grows quickly, so check /hooks and the reference if a field behaves differently in your version.
How hooks work
A hook has three levels: an event, a matcher, and one or more handlers.
- The event says when it runs.
PreToolUsefires after Claude has decided to call a tool and before the call runs.PostToolUsefires after a tool call succeeds. There are many others, includingSessionStart,UserPromptSubmit,Stop,PreCompactandSubagentStop. - The matcher filters by tool name.
Bashmatches only shell commands.Edit|Writematches either tool. Omit it, or use*, to match everything. - The handler is what runs. This tutorial uses
"type": "command", which runs a shell command.
Claude Code sends the hook a JSON object on standard input. For a PreToolUse call on the Bash tool it looks like this (trimmed):
{
"session_id": "abc123",
"cwd": "/home/you/project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": { "command": "npm test", "description": "Run test suite" },
"tool_use_id": "toolu_01ABC"
}
What the hook prints and how it exits decide what happens next:
| Exit code | Effect |
|---|---|
0 |
Success. JSON on stdout is read as a decision; plain text or nothing means “no opinion” and the normal permission flow continues. |
2 |
Blocking error. For PreToolUse, the tool call is cancelled and stderr is shown to Claude as the reason. |
Anything else, including 1 |
Non-blocking error. The action goes ahead and you see a hook error notice. |
Hooks live in settings files. Use .claude/settings.json to share them with the team through Git, .claude/settings.local.json for yourself in one project, or ~/.claude/settings.json for every project. The script paths below use ${CLAUDE_PROJECT_DIR}, which Claude Code sets to the project root, so the hook works whatever directory Claude has moved into.
1. Block destructive commands
Create .claude/hooks/block-dangerous.sh:
#!/usr/bin/env bash
# PreToolUse hook for Bash: refuse commands that are hard to undo.
set -euo pipefail
input=$(cat)
cmd=$(jq -r '.tool_input.command // ""' <<<"$input")
deny() {
jq -n --arg reason "$1" '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: $reason
}
}'
exit 0
}
# Recursive force delete anywhere in the command, including after && or ;
# Collects the short flags of every rm (rm -rf, rm -fr, rm -r -f) and checks for r and f.
rm_flags=$(grep -Eo '(^|[;&|[:space:]])rm([[:space:]]+-[a-zA-Z]+)+' <<<"$cmd" | sed -E 's/^.*rm//' | tr -d ' \t-' || true)
if [[ "$rm_flags" == *[rR]* && "$rm_flags" == *f* ]]; then
deny "rm -rf is blocked by a project hook. Delete specific files instead, or ask the user."
fi
# Rewriting shared Git history
if grep -Eq 'git[[:space:]]+push[^;&|]*(--force([^-]|$)|[[:space:]]-f([[:space:]]|$))' <<<"$cmd"; then
deny "Force push is blocked. Use --force-with-lease after asking the user."
fi
if grep -Eq 'git[[:space:]]+reset[[:space:]]+--hard' <<<"$cmd"; then
deny "git reset --hard discards work. Stash or commit first, or ask the user."
fi
exit 0
Make it executable and register it in .claude/settings.json:
chmod +x .claude/hooks/block-dangerous.sh
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-dangerous.sh"
}
]
}
]
}
}
The hook returns a structured deny rather than exiting 2. Both block the call. The JSON form lets you write the reason once and keeps stderr free for real errors. Claude sees the reason and usually picks a safer route, such as deleting a single build folder or asking you.
Test it before trusting it. You can feed the script a fake event without starting Claude:
echo '{"tool_name":"Bash","tool_input":{"command":"cd /tmp && rm -rf build"}}' \
| .claude/hooks/block-dangerous.sh
echo '{"tool_name":"Bash","tool_input":{"command":"ls -la"}}' \
| .claude/hooks/block-dangerous.sh; echo "exit $?"
The first prints the deny JSON. The second prints nothing and exits 0.
2. Format every edited file
A PostToolUse hook on Edit|Write runs after Claude changes a file. The file path is in tool_input.file_path. Create .claude/hooks/format.sh:
#!/usr/bin/env bash
# PostToolUse hook for Edit|Write: run the project formatter on the changed file.
set -uo pipefail
file=$(jq -r '.tool_input.file_path // ""')
[ -z "$file" ] || [ ! -f "$file" ] && exit 0
case "$file" in
*.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.md|*.mdx)
npx --no-install prettier --write "$file" >/dev/null 2>&1 ;;
*.py)
ruff format "$file" >/dev/null 2>&1 ;;
esac
exit 0
Register it next to the first hook:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-dangerous.sh" }
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh" }
]
}
]
}
}
The script always exits 0, so a formatter that fails never interrupts Claude. npx --no-install stops npm from downloading Prettier on the fly if the project does not have it. Formatting in a hook has a side benefit: diffs stay free of whitespace noise, which makes reviewing Claude’s changes faster.
If you would rather have Claude fix lint errors itself, run the linter instead and exit 2 with the errors on stderr. For PostToolUse, exit 2 cannot undo the edit (it already happened), but stderr is shown to Claude, which then corrects the file.
3. Log every shell command
An audit log is cheap and answers “what did the agent actually run?” after a long session. Add a second PostToolUse group with the Bash matcher:
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -c '{time: (now | todate), session: .session_id, cwd: .cwd, command: .tool_input.command}' >> \"${CLAUDE_PROJECT_DIR}/.claude/command-log.jsonl\""
}
]
}
Add .claude/command-log.jsonl to .gitignore. Each line records when, where and what:
{"time":"2026-11-20T10:14:03Z","session":"abc123","cwd":"/home/you/project","command":"npm test"}
Because this runs after the call, it only logs commands that ran. To also log blocked attempts, add the same command as a PreToolUse hook.
4. Check what is loaded
Run /hooks inside a session. It lists every configured hook by event, with the file it came from, so you can see whether a user-level hook is overriding a project one. If a hook seems not to fire:
- Check the matcher spelling. Tool names are case-sensitive:
Bash,Edit,Write,Read. - Run the script by hand with a sample event, as above.
- Start Claude with
claude --debugto see hook execution in the log. - Remember that a hook which prints something other than JSON on exit
0is treated as “no decision”.
Hooks and permissions together
Hooks do not replace permission rules. Claude Code evaluates deny and ask rules whatever a PreToolUse hook returns: a hook can add a block, but it cannot approve a call that a deny rule forbids. Use each for what it is good at:
- Permission rules for simple, declarative limits:
Bash(git push *)inask,Read(./.env)indeny. - Hooks for logic a rule cannot express: inspecting the full command, checking the branch name, calling an internal policy service.
Pitfalls
Slow hooks. A PreToolUse hook runs before every matching call. Keep it under a second. Put slow checks such as a full test run in a Stop hook instead, which runs once when Claude finishes a turn.
Hooks that read secrets. Hook scripts run with your user’s permissions and full environment. Review hooks in a cloned repository as carefully as any script, because a project’s .claude/settings.json can run code on your machine.
Silent failures. A hook that crashes with exit 1 lets the action through. Test the deny path, not just the allow path.
Over-blocking. If Claude keeps hitting the same block, your rule may be too broad or your instructions unclear. Read the reasons it gets and adjust.
Next steps
- Combine hooks with permission modes and the sandbox in Permissions and sandboxing for coding agents.
- The git-guardrails-claude-code skill sets up a similar Git hook for you.
- Hooks also run in headless mode, which matters when you run coding agents in CI.
- Keep the Claude Code hooks cheat sheet and coding agent cheat sheet open for events, matchers, exit codes and flags.
- Apply the same idea across a team with the guardrail hooks recipe for coding agents.
- New to the tool? Start with the Claude Code tutorial for your first session.
- Check how hooks behave when Claude writes code to call tools in Code Mode and programmatic tool calling.
Covers
- Tools
Check your understanding
Claude Code hooks quiz
Hook events, matchers, exit codes and JSON decisions, formatting and logging hooks, and how hooks work with permission rules.
7 questions · pass mark 70%
Review
Related
- Permissions and sandboxing for coding agents
Set up Claude Code permission modes and rules, the Codex sandbox and approvals, and a dev container, so an agent can work without free rein.
- Your first session with Claude Code
Install it, run it in a real repository, approve its first changes, commit a reviewed edit and learn the commands you will use daily.
- Git guardrails for Claude Code
Matt Pocock's skill that sets up a Claude Code hook to block destructive Git commands such as push, reset --hard, clean and branch -D before they run.
- Hooks
User-defined commands that run automatically at set points in a coding agent's lifecycle, such as before a tool call or when a session ends.
- Run coding agents headless in CI
Run claude -p and codex exec in GitHub Actions with pinned versions, narrow permissions, scoped secrets and separate jobs for writing back to the pull request.