我如何用 Pre-Tool Hooks 驯服 Claude Code(你也该如此)
Source: Dev.to
背景
我一直在使用 Claude Code 作为我的 AI 搭档程序员来构建 jo4.io——一个带有分析功能的 URL 短链接服务。生产力提升非常明显,但我很快注意到 Claude 在执行命令时有点……过于热情。
问题
在调试统计跟踪 bug 时,Claude 开始:
- 运行
cd /some/path命令,弄乱了我的终端工作目录 - 在我审查之前尝试
git commit和git push - 偶尔执行破坏性的 Git 命令,如
git reset --hard
Claude 本身并没有 bug——它只是按照自己认为有帮助的方式行事。然而在生产代码库中,我需要严格控制哪些内容会被提交和推送。
解决方案:PreToolUse 钩子
Claude Code 提供了一个强大且未被充分利用的功能——PreToolUse 钩子。它们可以在工具调用(例如 Bash 命令)执行之前拦截并阻止它们。
钩子配置(settings.json)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/block-git.sh",
"timeout": 10
},
{
"type": "command",
"command": "~/.claude/block-cd.sh",
"timeout": 10
}
]
}
]
}
}
阻止 cd 命令的脚本(block-cd.sh)
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command // empty')
trimmed_command=$(echo "$command" | sed 's/^[[:space:]]*//')
# Block standalone cd, allow (cd /path && command)
if [[ "$trimmed_command" =~ ^cd[[:space:]] ]]; then
cat "The fix is complete. When you’re ready, you can commit with:
> \`git commit -m 'Fix stats tracking by extracting request data before async'\`"
fi
Claude 不再自动提交和推送,而是把控制权交还给我。我审查了更改,运行了测试,满意后才提交。
观察到的好处
- 安全性 – 不会出现意外的强制推送或硬重置。
- 可审查性 – 我始终能看到将要提交的内容。
- 学习 – Claude 解释其意图的动作,帮助我学习。
- 信任 – 我可以在只读操作上授予 Claude 更多自主权,同时对写操作进行门控。
设置步骤
-
创建钩子目录
mkdir -p ~/.claude -
添加
settings.json(如上所示),放入~/.claude/settings.json。 -
创建 Shell 脚本(
block-git.sh和block-cd.sh)到~/.claude/。 -
赋予脚本可执行权限
chmod +x ~/.claude/*.sh -
重启 Claude Code 以加载新配置。
未来的钩子想法
- 阻止对敏感目录的
rm -rf。 - 对数据库迁移要求确认。
- 将所有命令记录到审计文件中。
钩子系统极其灵活:你可以匹配特定工具、检查命令内容,并返回自定义错误信息。
行动号召
你在使用 Claude Code 钩子吗?欢迎在评论中分享你的配置!
构建 jo4.io – 一个现代化的 URL 短链接服务,具备高级分析功能。敬请查看