Hooks 是 Claude Code 中最容易被忽视但最强大的功能之一。通过在关键事件点插入自定义脚本,你可以实现自动格式化、安全检查、提交消息生成,甚至一键部署。
Hooks 是什么?
Hooks 是在 Claude Code 操作的关键时间点自动执行的脚本。它们运行在你的机器上,拥有完整的系统权限。
生命周期事件
| 事件 | 触发时机 | 能做什么 |
|---|---|---|
| PreToolUse | 工具调用前 | 阻止危险操作 |
| PostToolUse | 工具调用后 | 格式化、lint |
| SessionStart | 会话开始 | 初始化环境 |
| UserPromptSubmit | 用户提交提示 | 修改/增强提示 |
| PermissionRequest | 权限请求 | 自动批准/拒绝 |
| Notification | 通知发送 | 转发到 Slack 等 |
| SubagentStart/Stop | 子 Agent 生命周期 | 监控和日志 |
配置方式
在 .claude/settings.json 中配置:
json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "prettier --write $CLAUDE_FILE_PATH"
}
]
}
]
}
}实战案例
案例 1:自动格式化(最常用)
Claude 每次编辑文件后自动运行 Prettier:
json
{
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
}
]
}
]
}案例 2:安全守卫(阻止危险操作)
在 Claude 执行命令前检查是否包含危险操作:
json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "scripts/safety-check.sh"
}
]
}
]
}safety-check.sh:
bash
#!/bin/bash
# 检查危险命令
if echo "$CLAUDE_TOOL_INPUT" | grep -qE 'rm -rf|drop table|force push'; then
echo '{"decision": "block", "reason": "Dangerous command detected"}'
exit 2
fi
exit 0PreToolUse 的 exit code 2 会阻止工具调用。
案例 3:自动生成 Commit 消息
json
{
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "scripts/auto-commit-msg.sh"
}
]
}
]
}案例 4:通知转发
将 Claude 的通知转发到 Slack:
json
{
"Notification": [
{
"hooks": [
{
"type": "command",
"command": "curl -X POST $SLACK_WEBHOOK -d '{\"text\": \"Claude: $CLAUDE_NOTIFICATION\"}'"
}
]
}
]
}案例 5:懒惰检测器(防止 Claude 偷懒)
检测 Claude 是否跳过了文件读取直接编辑:
json
{
"PreToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "scripts/laziness-guard.sh"
}
]
}
]
}这个 Hook 检查 Claude 在编辑文件前是否先读取了该文件。
Hook 输出协议
additionalContext
想要向 Claude 传递信息?在 Hook 输出中包含 additionalContext:
bash
echo '{"additionalContext": "File formatted successfully. No warnings."}'这段文字会直接进入 Claude 的上下文。注意:没有截断——保持输出简洁。
Exit Codes
| Exit Code | PostToolUse 行为 | PreToolUse 行为 |
|---|---|---|
| 0 | 静默成功 | 允许工具调用 |
| 1 | 错误报告 | 允许但报告错误 |
| 2 | stderr 作为错误 | 阻止工具调用 |
高级技巧
1. 环境变量
Hook 脚本可以访问这些环境变量:
$CLAUDE_FILE_PATH— 操作的文件路径$CLAUDE_TOOL_INPUT— 工具输入 JSON$CLAUDE_TOOL_OUTPUT— 工具输出 JSON$CLAUDE_SESSION_ID— 会话 ID
2. Matcher 语法
Write|Edit— 匹配 Write 或 Edit 工具Bash— 匹配 Bash 工具- 不设 matcher — 匹配所有工具调用
3. 插件中的 Hooks
通过插件分发 Hooks,使用 $CLAUDE_PLUGIN_ROOT 引用插件目录:
json
{
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/my-hook.sh"
}4. 性能考虑
- Hook 在每次匹配的工具调用时都执行
- 保持 Hook 脚本快速(< 1秒)
- 避免网络请求除非必要
原文整理自 Claude Code Hooks Guide | 来源:Claude Code 官方文档