0
0
GitHow-ToBeginner · 3 min read

How to Use Pre-Push Hook in Git: Setup and Examples

Use a pre-push hook by creating an executable script named pre-push inside the .git/hooks/ directory. This script runs automatically before git push and can stop the push if it exits with a non-zero status.
📐

Syntax

The pre-push hook is a script placed in the .git/hooks/ folder of your repository. It runs before the push happens. If the script exits with 0, the push continues; if it exits with any other code, the push is stopped.

The script receives two parameters: the name of the remote and the URL of the remote. It can also read from standard input the list of refs to be pushed.

sh
#!/bin/sh
# pre-push hook script
# Parameters:
# $1 = name of the remote
# $2 = URL of the remote

while read local_ref local_sha remote_ref remote_sha
 do
   echo "Pushing $local_ref ($local_sha) to $remote_ref ($remote_sha)"
 done

# Exit 0 to allow push
exit 0
💻

Example

This example pre-push hook checks if any Python files have syntax errors before allowing the push. If errors are found, it stops the push and shows the error.

sh
#!/bin/sh
# Check Python syntax before push

# Read refs from stdin
while read local_ref local_sha remote_ref remote_sha
 do
   # Find changed Python files
   files=$(git diff --name-only $remote_sha $local_sha | grep '\.py$')
   if [ -n "$files" ]; then
     for file in $files; do
       python3 -m py_compile "$file"
       if [ $? -ne 0 ]; then
         echo "Syntax error in $file. Push aborted."
         exit 1
       fi
     done
   fi
 done

exit 0
Output
Syntax error in example.py. Push aborted.
⚠️

Common Pitfalls

  • Not making the pre-push script executable will prevent it from running.
  • Assuming the hook runs in the root directory; it runs with the repository root as the current directory.
  • Not handling input correctly from stdin can cause the hook to miss pushed refs.
  • Exiting with 0 always will never stop a bad push.
sh
# Wrong: script not executable
# chmod +x .git/hooks/pre-push

# Wrong: ignoring stdin input
#!/bin/sh
exit 0

# Right: reading stdin and exiting non-zero on error
#!/bin/sh
while read local_ref local_sha remote_ref remote_sha
 do
  # your checks here
 done
exit 1  # stops push if error found
📊

Quick Reference

ActionDescription
Create hookAdd executable script named pre-push in .git/hooks/
Script runsBefore git push, receives remote name and URL as args
Read refsRead pushed refs from stdin (local_ref local_sha remote_ref remote_sha)
Exit codesExit 0 to allow push, non-zero to stop push
Make executableRun chmod +x .git/hooks/pre-push

Key Takeaways

Place an executable script named pre-push in .git/hooks/ to run before pushing.
The script receives remote info as arguments and pushed refs on stdin.
Exit with 0 to allow push; exit non-zero to stop it.
Always make the hook script executable with chmod +x.
Use the hook to run checks like tests or lint before code is pushed.