Git Hooks

Divya Srinivasan

What are Git Hooks?

Git hooks are scripts that run automatically at key points in your Git workflow, like when you commit or push code.

They let you automate tasks, check for issues, and enforce standards before changes are accepted.

Why Use Git Hooks?

Hooks help you:
  • Catch problems early (e.g., failing tests, bad commit messages)
  • Enforce coding standards
  • Automate repetitive checks
  • Improve team consistency

Where Do Hooks Live?

Hooks live inside each repository at:

.git/hooks
By default, you’ll find sample scripts there (with .sample extensions).

Listing Available Hooks

To see all available hook templates:
ls .git/hooks

How to Enable a Hook

To activate a hook, remove the .sample extension and make it executable.

Example (Linux/macOS):

mv .git/hooks/pre-commit.sample .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
On Windows:
Rename the file (e.g., pre-commit) and use a format your shell can run (.bat, .ps1, etc.).


Common Types of Hook:



Hook Examples

pre-commit Hook
Run before you commit. Can stop the commit if something’s wrong.
#!/bin/sh
# Block commit if any .js file contains "console.log"
if grep -r 'console.log' *.js; then
  echo "Remove console.log before committing!"
  exit 1
fi
commit-msg Hook
Validate commit message format.
#!/bin/sh
# Require a ticket number in the message (e.g., JIRA-123)
if ! grep -qE 'JIRA-[0-9]+' "$1"; then
  echo "Commit message must include a ticket number (e.g., JIRA-123)"
  exit 1
fi
pre-push Hook
Run tests before pushing code.
#!/bin/sh
npm test || exit 1
Server-side pre-receive Hook
Run on the remote server to block changes to main branch.
#!/bin/sh
while read oldrev newrev refname; do
  if [ "$refname" = "refs/heads/main" ]; then
    echo "Direct pushes to main are blocked!"
    exit 1
  fi
done

Custom Hooks

You can write any script (Bash, Python, etc.) as a hook.
Just put it in .git/hooks and make it executable.

Example:

#!/bin/sh
echo "Hello from my custom hook!"

Best Practices & Debugging

  • Make sure scripts are executable:
chmod +x .git/hooks/hookname
  • Use echo statements to see what’s happening.
  • Exit codes matter:
exit 0 → success; exit 1 → fail.
  • Keep hooks fast—slow hooks slow you down.
  • Share hooks: add them to your repo or use tools like Husky to manage hooks in a team.

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send