Skip to main content

Git Hooks & Automation

Git hooks are scripts that run automatically every time a particular event occurs in a Git repository.

What are Git Hooks?

Hooks are stored in the .git/hooks directory. They are shell scripts that can run before or after Git actions.

Common Hooks

HookWhen it runsUse Case
pre-commitBefore git commitLinting, formatting, running unit tests.
commit-msgAfter entering messageEnforcing commit message patterns (e.g., “JIRA-123: …“).
pre-pushBefore git pushRunning integration tests, preventing accidental push to main.

Creating a Hook (Manual)

Create a file .git/hooks/pre-commit:
#!/bin/sh
echo "Running pre-commit checks..."

# Run linter
npm run lint

# If linter fails ($? is exit code), stop commit
if [ $? -ne 0 ]; then
    echo "Linting failed! Commit aborted."
    exit 1
fi
Make it executable:
chmod +x .git/hooks/pre-commit

Automating with Husky (JavaScript/Node)

Sharing hooks via .git/hooks is hard because that directory isn’t committed. Husky solves this by configuring hooks in your project files.

1. Install Husky

npm install --save-dev husky
npx husky init

2. Add a Hook

This creates a .husky/pre-commit file.
echo "npm test" > .husky/pre-commit
Now, every time you run git commit, npm test will run first. If it fails, the commit fails.

Lint-Staged

Running tests on the entire project for every commit is slow. lint-staged allows you to run scripts only on the files that are currently staged. package.json:
{
  "lint-staged": {
    "*.{js,ts}": "eslint --fix",
    "*.{md,json}": "prettier --write"
  }
}
.husky/pre-commit:
npx lint-staged

Key Takeaways

  • Use Hooks to shift quality checks “left” (to the developer’s machine).
  • Use Husky to share hooks across your team.
  • Use Lint-Staged to keep commits fast.
  • Don’t rely only on hooks (developers can bypass them with git commit --no-verify). Always run checks in CI too.

Next: Linux Crash Course →