Skip to content

Hook

一句话解释

Git Hook 是自定义 scripts 那个 Git automatically 执行 at 特定点 in workflow, 如之前提交 or 之后合并.

用大白话说

Git Hook 是 scripts 存储 in .git/hooks/ that Git runs automatically at specific events. They let you enforce policies, run tests, format code, or send notifications without manual intervention.

Common hooks: pre-提交 (runs before a commit is created — use to lint or run tests), pre-推送 (runs before a push — use to prevent pushing broken code), post-合并 (runs after a merge — use to install dependencies), and 提交-msg (runs to validate commit message format).

Hooks are local to each repository and are not version-controlled by default (they live in .git). Teams often use tools like Husky (for JavaScript projects) to share hooks via package.json. Hooks can be any executable script — shell, Python, Node.js, etc.

示例

bash
# Sample .git/hooks/pre-commit
#!/bin/sh
# Run tests before allowing commit
npm test
if [ $? -ne 0 ]; then
  echo "Tests failed — commit aborted"
  exit 1
fi

# Make it executable
chmod +x .git/hooks/pre-commit

pre-提交 Hook 运行测试之前每个提交, aborting on 失败.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表