Skip to content

Instantly share code, notes, and snippets.

@eik3
Last active February 11, 2022 09:48
Show Gist options
  • Save eik3/e62ec04addafcc884176997d3f90fa96 to your computer and use it in GitHub Desktop.
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
  1. Save files to ~/.git/hooks/
  2. Make them executable: chmod +x ~/.git/hooks/pre-{commit,push}
  3. Configure git to use these hooks: git config --global core.hooksPath ~/.git/hooks
#!/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
#!/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