Week 7 of 12 🪝
Hooks และระบบอัตโนมัติ
Hooks 与自动化
Click a card to flip it. คลิกการ์ดเพื่อพลิก 点击卡片翻面。
What exit code blocks an action?
Exit code อะไรบล็อกการดำเนินการ?
哪个退出码会拦截操作?
Where are hooks configured?
Hooks ตั้งค่าที่ไหน?
Hooks 在哪里配置?
Complete: ___ you save, the hook runs.
เติม: ___ you save, the hook runs.
填空:___ you save, the hook runs.
How to do it
/hooks to list every configured hook and the event it fires on.PreToolUse (before a tool runs) and PostToolUse (after).How to do it
~/.claude/settings.json under the "hooks" key.How to do it
rm -rf before they ever run.How to do it
How to do it
echo ... >> hook.log) so you can see each run.A hook is a normal program that Claude Code runs at a fixed moment. The whole mechanism is four steps:
Edit on app.py).matcher matches this tool? ("Edit|Write" is a regex — it matches both tools.)| Exit code | PreToolUse | PostToolUse |
|---|---|---|
0 | allow the tool | all good |
2 | block the tool — it never runs | send feedback to Claude |
| other | hook failed — shown to you, but the tool continues | |
This one appends every edited file's path to changes.log — a diary of what
Claude touched. Add it to ~/.claude/settings.json:
Reading the command: python loads the JSON from stdin (json.load(sys.stdin)),
pulls out tool_input.file_path, and appends it to the log file. Ask Claude to edit
anything, then Read changes.log — your hook wrote a line. When it works, try the
next level: change the event to PreToolUse and exit with code 2 to build a
command-blocker.
Step by step
✓ You did it right if: changes.log contains the path of the file that was just edited.
// Save as: ~/.claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python -c \"import json,sys; d=json.load(sys.stdin); open('changes.log','a').write(d['tool_input'].get('file_path','?')+'\\n')\""
}
]
}
]
}
}
// How it works: after every Edit or Write, Claude Code runs the
// command and sends the tool call as JSON on stdin. The file path
// is in tool_input.file_path.
# ---- Test it ----
> add a comment to the top of app.py
* Edit(app.py) ... Allow? > y (the hook fires silently after)
> Read changes.log
1 app.py <- the hook logged your edit
| Command / Tool | English | ภาษาไทย | 中文 |
|---|---|---|---|
PreToolUse | Before a tool runs | ก่อนเครื่องมือทำงาน | 工具运行之前 |
PostToolUse | After a tool succeeds | หลังเครื่องมือทำงานสำเร็จ | 工具成功之后 |
SessionStart | When a session begins | เมื่อเซสชันเริ่มต้น | 会话开始时 |
Notification | Claude needs attention | Claude ต้องการความสนใจ | Claude 需要你的注意 |
Stop | Claude finishes responding | Claude ตอบเสร็จ | Claude 完成回复 |
Wire up a pre-hook and a post-hook, then try to sneak a dangerous command past them. / ลองตั้ง hooks แล้วดูมันทำงาน / 配置 hooks 并观察它们工作
Configure hooks, pick an action, press Run. Watch the pipeline decide.