Claude Code Hooks: tự động format, chặn lệnh nguy hiểm, ép chạy test — không cần nhắc
Tóm tắt
Hook là lệnh shell (hoặc HTTP, prompt…) chạy tại các sự kiện như PreToolUse, PostToolUse, Stop. Exit code 2 ở PreToolUse chặn tool call và gửi lý do cho Claude; ở Stop thì buộc Claude làm tiếp. Cấu hình trong .claude/settings.json, xem bằng /hooks.
Ví dụ 1: tự format sau khi sửa file
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "npx prettier --write \"$(jq -r .tool_input.file_path)\"" }]
}]
}
}Ví dụ 2: chặn rm -rf
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{ "type": "command", "if": "Bash(rm *)",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh" }]
}]
}
}
# block-rm.sh
echo "Không được xoá file bằng rm. Hãy hỏi người dùng." >&2
exit 2Exit code quan trọng
| Sự kiện | Exit 2 nghĩa là |
|---|---|
| PreToolUse | Chặn tool, stderr thành lý do cho Claude |
| PostToolUse | Không chặn (tool đã chạy), stderr gửi cho Claude |
| Stop | Không cho Claude dừng — ví dụ khi test còn đỏ |
- Exit 1 không chặn — dùng exit 2 cho luật bắt buộc.
- Hook ở
.claude/settings.jsoncommit cùng repo để cả team dùng chung. - Tạm tắt tất cả:
"disableAllHooks": true.
Tài liệu: Hooks reference · Hooks guide