Claude Code hooks examples: block and format
Working Claude Code hooks examples: block a destructive Bash command in PreToolUse, format files after edits in PostToolUse, and test each hook by hand.
These Claude Code hooks examples block a destructive Bash command in a PreToolUse hook and format files in a PostToolUse hook. A hook is a command that Claude Code runs at a fixed point in a session. You register it in .claude/settings.json, and the command receives the event as JSON on standard input. A PreToolUse hook that exits with code 2 blocks the call, and whatever it wrote to stderr goes back to Claude as the reason, as Anthropic's hooks guide explains.
How do you configure a Claude Code hook?
Settings nest three levels deep: an event name, a matcher group, and a list of handlers. The matcher says which tool the hooks apply to. Bash matches the Bash tool, Edit|Write matches either file tool, and an empty matcher matches everything. A matcher made only of letters, digits, _, -, | and commas is read as exact tool names. Anything else is read as a regular expression, according to the hooks reference.
Put project hooks in .claude/settings.json so they travel with the repository, and personal ones in .claude/settings.local.json, which stays out of git. Your script finds the project through CLAUDE_PROJECT_DIR. In a shell-form command, quote it: "$CLAUDE_PROJECT_DIR"/.claude/hooks/block-drop.sh.
The event decides when the hook runs. These are the ones these examples and most projects use:
| Event | Runs | Can it block? |
|---|---|---|
SessionStart |
When a session starts | No. Used to print context |
UserPromptSubmit |
When you submit a prompt | Yes |
PreToolUse |
Before a tool runs | Yes. Exit 2 refuses the call |
PostToolUse |
After a tool succeeds | No. The tool already ran |
Stop |
When Claude finishes responding | Yes. Exit 2 makes Claude keep working |
The reference lists more events, including SubagentStop, PreCompact and SessionEnd.
Claude Code hooks example: block a dangerous command
This hook refuses any Bash command containing drop table. Save it as .claude/hooks/block-drop.sh and run chmod +x on it:
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$COMMAND" | grep -qi "drop table"; then
echo "Blocked: dropping tables is not allowed. Ask the user first." >&2
exit 2
fi
exit 0Register it for the Bash tool:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-drop.sh"
}
]
}
]
}
}You can test the script without starting Claude, because it only reads JSON from stdin. This is the same shape of payload Claude Code sends:
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"psql -c \"DROP TABLE users\""}}' | ./.claude/hooks/block-drop.sh; echo "exit=$?"Blocked: dropping tables is not allowed. Ask the user first.
exit=2A harmless command such as npm test prints nothing and exits 0. Exit 0 doesn't approve the call. It means this hook has no opinion, so Claude's normal permission rules still decide.
The script has two weaknesses. It matches text anywhere in the command, so it would also refuse an echo or a commit message that mentions dropping a table. And if jq isn't installed, COMMAND is empty and the script exits 0, so the guard silently allows everything.
The second way to deny is to exit 0 and print JSON instead of using the exit code. The permissionDecision can also be ask, which prompts you instead of refusing:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Dropping tables is not allowed"
}
}Pick one style per hook, as the guide advises. Exit 2 with a stderr message is the shorter script.
A text match catches accidents, not intent. A command that builds the string some other way, such as psql -c "dr""op table users", gets past it. The guide says a hook's if filter is best-effort and recommends permission rules for anything that must be a hard deny. Use both: the hook for a useful message, a permissions.deny entry for the guarantee.
Claude Code hooks example: format a file after Claude edits it
A PostToolUse hook runs after a tool succeeds. Matching Edit|Write lets it react to every file Claude changes. This is the formatter example from Anthropic's guide, which reads the edited path from the payload and runs Prettier on it:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}--ignore-unknown keeps Prettier quiet about file types it doesn't handle, such as a Makefile. A PostToolUse hook can't undo the edit, because the tool has already run. It can still reach Claude: when it exits with code 2, its stderr is shown to Claude, which is how you report a lint error for the agent to fix next.
Formatting after every single edit has a cost. The formatter rewrites the file, so Claude's next edit may target text that no longer matches what it remembers. Formatting once at the end of the turn avoids that. A Stop hook does it, and a Stop hook that exits 2 also makes Claude keep working until a check passes. Add a guard against looping, using the stop_hook_active field in its input. The guide to making Claude Code run tests before it stops has a complete script.
Are Claude Code hooks safe to copy from a repository?
Treat a hook like any other script you run on your machine. Command hooks run with your user account's permissions, outside Claude's permission rules, so a hook can read or delete anything you can. Read the scripts in a repository's .claude/ folder before you open it in Claude Code, the same way you would read an install script.
To see what is configured, run /hooks inside a session. To debug one, skip Claude and feed the script a sample payload as above. Most hook bugs are in the script: a missing jq, a file that isn't executable, or a command that only works from a different directory.
Should a guard hook fail open or closed?
A hook that exits with any code other than 0 or 2 is a non-blocking error: the action goes ahead and the transcript shows a notice. That makes fail-open the default. The cost is that a guard that crashes, for example on a machine without jq, stops guarding without anyone noticing. Newer Claude Code versions let a hook set "onFailure": "block", which makes the action fail when the hook itself fails. Check the hooks reference for your version before relying on it.
The hooks that stacks ships fail open on purpose. When a guard can't run, it prints hook unavailable; allowing this call to stderr and exits 0, because a broken guard that blocked every command would stop all work. The tradeoff is real, so the fragment adds a separate test that exercises the guards, described next.
Getting a tested set of hooks with stacks
Writing guard patterns from scratch is the slow part. The agent-ops fragment in stacks ships a set that has a test of its own, and you can add it to an existing repository:
stacks add agent-ops --no-launchIt writes these files under .claude/hooks/ and wires them in .claude/settings.json: block-destructive.sh for commands like rm -rf ~, force pushes and dropped tables, detect-secrets.sh for writes that contain credentials or touch .env, lint-on-write.sh after edits, and format-changed.sh at Stop. Here is the deny that block-destructive.sh returned in a scratch project when given a force push:
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"BLOCKED: This git command rewrites history or deletes remote branches. Ask the user first. Never work around this block."}}The fragment also adds a verify step named hooks-smoke, which runs bash .claude/hooks/smoke.sh. That script feeds each guard a command it should deny and a near miss it should allow, so a change to a pattern that breaks the guard fails stacks verify instead of surfacing during a real session. The guards match text, so the stacks documentation describes them as accident prevention that doesn't stop a determined workaround. Run stacks show agent-ops --kind fragment to read the full list of files before you add it.
Add agent guardrails to this existing Go repo. Keep its project rules.
I’ll inspect the existing rules and check whether the TypeScript harness fits.
●Bash(cat AGENTS.md)
●Bash(stacks show claude-harness)
claude-harness targets Bun TypeScript projects. This is a Go CLI, so I’ll add agent-ops alone.
●Bash(stacks add agent-ops --no-launch)
●Bash(find .claude -type f | sort)
●Bash(cat .stacks/incoming/AGENTS.md)
●Bash(cat AGENTS.md)
The hooks are written. My existing AGENTS.md is unchanged; stacks parked its template and Claude settings under .stacks/incoming/. I’ll merge those next, then verify.