- Save files to
~/.git/hooks/
- Make them executable:
chmod +x ~/.git/hooks/pre-{commit,push}
- Configure git to use these hooks:
git config --global core.hooksPath ~/.git/hooks
Last active
February 11, 2022 09:48
-
-
Save eik3/e62ec04addafcc884176997d3f90fa96 to your computer and use it in GitHub Desktop.
Git pre-commit and pre-push hooks to avoid accidental main / master branch commits / pushes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# This hook asks the user for confirmation before committing to the main/master branch | |
current_branch="$(git branch --show-current)" | |
protected_branch_regex='^(main|master)$' | |
if [[ "$current_branch" =~ $protected_branch_regex ]]; then | |
prompt="You're about to commit to ${current_branch}, is that what you intended? [y|n] " | |
read -p "${prompt}" -n 1 -r response < /dev/tty | |
echo | |
if echo "${response}" | grep --extended-regexp '^[Yy]$' > /dev/null; then | |
exit 0 # commit will execute | |
fi | |
exit 1 # commit will be aborted | |
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# This hook asks the user for confirmation before pushing the main/master branch | |
current_branch="$(git branch --show-current)" | |
protected_branch_regex='^(main|master)$' | |
if [[ "$current_branch" =~ $protected_branch_regex ]]; then | |
prompt="You're about to push ${current_branch}, is that what you intended? [y|n] " | |
read -p "${prompt}" -n 1 -r response < /dev/tty | |
echo | |
if echo "${response}" | grep --extended-regexp '^[Yy]$' > /dev/null; then | |
exit 0 # push will execute | |
fi | |
exit 1 # push will be aborted | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment