A Git pre-commit hook that prevents accidental commits on protected branches (master, main, production).
β
π΄ Warning when committing on a protected branch.
β
π’ Option to proceed (yes) or discard uncommitted changes (discard).
β
π‘ Default is no (commit aborted unless explicitly confirmed).
β
π Logs commit attempts in ~/.git_commit_log.txt for auditing.
β
π¨ Color-coded output for better readability.
- If you attempt to commit on a protected branch (
master,main,production), a warning appears. - You can:
- Type
yesβ Proceed with the commit. - Type
discardβ Discard all uncommitted changes (tracked & untracked). - Press Enter (
no) β Abort the commit (default action).
- Type
- All commit attempts are logged in
~/.git_commit_log.txt.
-
Navigate to your repository:
cd /path/to/your/repository -
Place the script inside
.git/hooks/pre-commit:
nano .git/hooks/pre-commit-
Paste the pre-commit script and save.
-
Make it executable:
chmod +x .git/hooks/pre-commit- Create a global hooks directory:
mkdir -p ~/.git_hooks- Tell Git to use this hooks directory globally:
git config --global core.hooksPath ~/.git_hooks- Create the pre-commit hook:
nano ~/.git_hooks/pre-commit- Paste the script, save, and make it executable:
chmod +x ~/.git_hooks/pre-commit