How to use Git hooks
Git hooks automate workflow tasks by executing custom scripts at specific points in your Git workflow, from linting code before commits to running tests before pushes.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented Git hooks in development workflows throughout my 25 years of software development experience.
The most straightforward approach is creating executable scripts in the .git/hooks directory that Git automatically triggers at defined events.
This method enforces code quality and consistency without manual intervention.
Create executable shell scripts in the .git/hooks directory for automated workflow tasks.
cd .git/hooks
touch pre-commit
chmod +x pre-commit
Here you navigate to the hooks directory, create a new hook file (like pre-commit), and make it executable. Edit the file to add your script, for example:
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed. Commit aborted."
exit 1
fi
This pre-commit hook runs linting before each commit. If linting fails (non-zero exit code), the commit is aborted. Git provides hooks for various events including pre-push, post-commit, pre-rebase, and more.
Best Practice Note:
This is the approach we use in CoreUI repositories to enforce code quality standards before commits reach the repository.
Use tools like Husky to share hooks across teams via package.json, as .git/hooks is not tracked by Git, and keep hook scripts fast to avoid slowing down developer workflows.



