0
0
GitHow-ToBeginner · 3 min read

How to Use Git Post-Commit Hook: Simple Guide

A post-commit hook in Git is a script that runs automatically after a commit is made. To use it, create an executable script named post-commit inside the .git/hooks/ directory of your repository. This script can perform tasks like notifications or cleanup right after each commit.
📐

Syntax

The post-commit hook is a script file placed in the .git/hooks/ folder of your Git repository. It must be executable and named exactly post-commit without any extension.

When you run git commit, Git automatically runs this script after the commit is saved.

The script can be written in any language supported by your system (bash, python, etc.) but usually is a shell script.

sh
#!/bin/sh
# This is the post-commit hook script
# Add commands you want to run after commit here
💻

Example

This example shows a simple post-commit hook that prints a message after each commit.

sh
#!/bin/sh

echo "Commit completed successfully!"
Output
Commit completed successfully!
⚠️

Common Pitfalls

  • Not making the post-commit script executable will prevent it from running. Use chmod +x .git/hooks/post-commit.
  • Placing the script outside .git/hooks/ folder means Git won't find it.
  • Using Windows line endings (CRLF) in the script on Unix systems can cause errors; use LF endings.
  • Scripts that take too long or fail silently can disrupt your workflow.
sh
# Wrong: script not executable
# .git/hooks/post-commit (no execute permission)

# Right: make executable
chmod +x .git/hooks/post-commit
📊

Quick Reference

StepDescription
Create scriptMake a file named post-commit in .git/hooks/
Write commandsAdd shell commands to run after commit
Make executableRun chmod +x .git/hooks/post-commit
TestMake a commit and see the hook run

Key Takeaways

Place your post-commit script in .git/hooks/ and name it exactly post-commit.
Make the script executable with chmod +x to ensure it runs.
Use the post-commit hook to automate tasks right after a commit finishes.
Avoid Windows line endings and long-running commands in the hook script.
Test your hook by making a commit and checking the output or effects.