匠人学院 JR Academy学AI来匠人
匠人学院 JR Academy学AI来匠人

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
EN

关于公司

关于我们元宇宙课堂新闻资讯匠人工作成为导师匠人导师联系我们匠人商店J3.Club

匠人资源

工作内推匠人活动1对1私教行业白皮书线上学习平台面试中心分享面试经验Internship会员中心

AI 工具

AI 工具箱考证匠 Cert Master求职匠 Job Hunter牛小匠 UniMate AI

AI 学习方向

全部学习方向AI EngineerContext EngineeringVibe CodingPrompt MasterAI BuilderAI 产品经理Python 入门

AI 应用提效

AI 办公提效AI 数据分析AI 财务AI 内容创作AI 视觉创作前端开发Hermes AgentOpenClaw 本地智能体

大学资源

墨尔本大学昆士兰大学新南威尔士大学悉尼大学莫那什大学阿德莱德大学RMITQUTUTS

少儿 AI 教育

Airbotix 少儿 AI 编程澳洲家长实用资料库NAPLAN 成绩单怎么看My School 学校数据指南悉尼私校学费 2026少儿编程课程与训练营

移民服务

澳洲移民技术移民189/190/491雇主担保482/186/494投资移民188/888英国移民美国移民加拿大移民

企业合作

P3职业孵化器Enterprise (EN)企业培训实习合作招聘合作申请合作

求职代理

岗位代投职位监控LinkedIn代运营LinkedIn人脉代加了解P3项目

匠人支持

FAQsTerms & ConditionsPrivacy PolicyCancellation & Refund PolicySite map

Top Categories

Web全栈班DevOps项目班数据工程全栈班数据分析项目班编程入门班Business Analyst实习算法集训营

求职就业

BA和产品经理实习数据科学实习数据分析实习Marketing实习简历修改面试指导导师指导VIP

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

联系方式

hello@jiangren.com.au0421-672-555

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

首页/资源中心/文章详情
JR Academy · Blog职业洞察

Claude Code 从入门到实战 — Hooks 自动化:让 Claude Code 在对的时机干对的事

用 Hooks 在 Claude Code 执行动作前后自动触发脚本,实现代码格式化、测试、安全检查全自动化

发布日期2026-08-24
阅读时长2 分钟
作者

快速导航

  • 什么是 Hooks
  • 两种 Hook 时机
  • 实战 1:改完代码自动格式化
  • 实战 2:提交前自动跑测试
  • 实战 3:保护 .env 文件不被改动
  • Hook 脚本收到的 JSON 格式
  • 常见坑
  • 推荐的项目级配置

什么是 Hooks

Hooks 生命周期

Hooks 是 2026 年初发布的功能,让你在 Claude Code 执行特定动作前后自动触发自定义脚本。

Claude Code 改了文件?自动跑 lint。
Claude Code 要写某个敏感文件?先问你要不要允许。

配置在 ~/.claude/settings.json(全局)或 .claude/settings.json(项目级):

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_TOOL_INPUT_FILE_PATH"
          }
        ]
      }
    ]
  }
}

两种 Hook 时机

时机 触发点 能否阻止操作 典型用途
PreToolUse Claude 要执行某操作之前 ✅ 可以 安全门控、保护文件、强制审批
PostToolUse Claude 执行完某操作之后 ❌ 不能(已完成) 格式化、跑测试、发通知

实战 1:改完代码自动格式化

每次 Claude Code 写文件,自动跑 Prettier:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_TOOL_INPUT_FILE_PATH 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

$CLAUDE_TOOL_INPUT_FILE_PATH 是 Claude Code 自动注入的环境变量,值是本次操作的文件路径。

实战 2:提交前自动跑测试

PreToolUse 拦截 Bash 命令,凡是含 git commit 的先跑测试:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash ~/.claude/hooks/pre-commit-check.sh"
          }
        ]
      }
    ]
  }
}

~/.claude/hooks/pre-commit-check.sh:

#!/bin/bash
# 读取 Claude Code 传入的 JSON,判断是否是 git commit 命令
input=$(cat)
command=$(echo "$input" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('command',''))")

if echo "$command" | grep -q "git commit"; then
  echo "检测到 git commit,先跑测试..."
  npm test
  if [ $? -ne 0 ]; then
    echo "测试失败,阻止提交" >&2
    exit 1  # 非零退出码 = 阻止 Claude Code 继续执行
  fi
fi

退出码非零 → PreToolUse Hook 阻止 Claude Code 执行后续操作。这是唯一能"拦截"的时机。

实战 3:保护 .env 文件不被改动

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "python3 -c \"\nimport json, sys\nd = json.load(sys.stdin)\npath = d.get('file_path', '')\nif '.env' in path and '.env.' not in path:\n    print(f'拒绝修改敏感文件: {path}', file=sys.stderr)\n    sys.exit(1)\n\""
          }
        ]
      }
    ]
  }
}

Hook 脚本收到的 JSON 格式

Claude Code 通过 stdin 传入上下文,你可以读取:

import json, sys

data = json.load(sys.stdin)
print(data.keys())
# 常见字段:
# - tool_name: "Write" / "Edit" / "Bash" / ...
# - file_path: 操作的文件路径
# - command: Bash 执行的命令
# - session_id: 当前会话 ID

常见坑

坑 1:PostToolUse 里用了退出码 1 试图阻止操作
→ 不行。PostToolUse 已经执行完,退出码只影响 Claude Code 是否报错,不能撤销操作。

坑 2:Hook 脚本没有可执行权限

chmod +x ~/.claude/hooks/your-hook.sh

坑 3:matcher 写错,Hook 没触发
matcher 是正则表达式,工具名包括:Write、Edit、Bash、Read、Glob、Grep、Agent。
用 "matcher": "Write|Edit" 匹配写操作,"matcher": ".*" 匹配所有工具。

推荐的项目级配置

在项目 .claude/settings.json 放这个,团队所有人共享:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          { "type": "command", "command": "npx prettier --write $CLAUDE_TOOL_INPUT_FILE_PATH 2>/dev/null || true" },
          { "type": "command", "command": "npx eslint --fix $CLAUDE_TOOL_INPUT_FILE_PATH 2>/dev/null || true" }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          { "type": "command", "command": "node .claude/hooks/protect-sensitive-files.js" }
        ]
      }
    ]
  }
}

一旦配置好,Claude Code 做任何修改都会自动走你团队的质量门控,不需要每次提醒它。

作者
一键分享或复制链接
Lightman Wang
Reviewer: Lightman Wang

Founder of JR Academy

查看该作者的更多文章 →

相关学习资源

  • Vibe Coding Hub
  • Prompt 工程入门
← 上一篇Claude Code 从入门到实战 — Git 工作流自动化下一篇 →Claude Code 从入门到实战 — MCP 服务器:给 Claude Code 装上超能力插件

相关文章推荐

最近关心AI Engineer的,真的要盯住澳洲🆓AI大会

2026-09-17

悉大COMP5318学什么?一篇理清核心知识点

2026-09-17

🇦🇺好消息!悉大留子可以🆓试用GPTEdu

2026-09-15

所有澳留快查❗你的学费也能退税!

2026-09-14

Claude直接送开发者6个月Max额度❗

2026-09-09

OpenAI开发者大会❗人在澳洲也能看

2026-09-08
查看全部文章 →
JR Academy
全球华人学习 AI 第一站
✓15000+ 学员
✓50+ 课程
✓AI 驱动学习平台
训练营免费资源AI学习职业辅导
精选推荐
AI 职业影响地图
测测你的职业风险等级,查看转型路径与学习方向
热门工具
AI & 数据训练营
系统化课程 + 真实项目实战,快速提升竞争力
热门课程
1v1 就业辅导
资深导师一对一指导,简历优化 + 面试准备
就业保障
企业内训定制
AI 技能培训方案,助力团队升级
企业服务
热门标签
Vibe CodingAI 编程CursorClaude求职攻略Prompt前端开发后端开发
订阅更新

获取最新 AI 学习资源、技术教程和求职攻略,直接送达邮箱。

我们尊重您的隐私,不会发送垃圾邮件