How to create pre-commit hook in Git

Pre-commit hooks automatically validate code before commits are created, ensuring code quality and preventing broken code from entering your repository. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented pre-commit hooks in development workflows throughout my 25 years of software development. The most straightforward approach is creating an executable script in the .git/hooks directory that runs linting and tests. This method enforces quality standards automatically without manual intervention.

Create an executable pre-commit script in .git/hooks to run validation checks.

#!/bin/sh

echo "Running pre-commit checks..."

npm run lint
if [ $? -ne 0 ]; then
  echo "Linting failed. Please fix errors before committing."
  exit 1
fi

npm run test
if [ $? -ne 0 ]; then
  echo "Tests failed. Please fix failing tests before committing."
  exit 1
fi

echo "All checks passed!"
exit 0

Here the script runs linting first, checking the exit code to determine success or failure. If linting fails (non-zero exit code), the script exits with code 1, aborting the commit. If linting passes, tests run next with the same validation. Only when all checks pass does the script exit with code 0, allowing the commit to proceed.

Best Practice Note:

This is the validation workflow we enforce in CoreUI repositories to maintain code quality across all commits. Use Husky to share hooks across teams via package.json instead of manual .git/hooks setup, keep hooks fast to avoid slowing down commits, and consider running full tests only in CI while running quick checks in pre-commit.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team