Skip to content

Instantly share code, notes, and snippets.

@ColCh
Last active September 26, 2024 08:12
Show Gist options
  • Save ColCh/9d48693276aac50cac37a9fce23f9bda to your computer and use it in GitHub Desktop.
Save ColCh/9d48693276aac50cac37a9fce23f9bda to your computer and use it in GitHub Desktop.
Git pre-push hook to confirm pushing to master

Git pre-push hook

It will check if current branch is master, then ask a confirmation, in case of master branch

Articles with initial info: https://dev.ghost.org/prevent-master-push/, https://coderwall.com/p/jp7d5q/create-a-global-git-commit-hook

Demo

http://imgur.com/a/EXGAW

To install

  1. Enable git templates
git config --global init.templatedir '~/.git-templates'

  1. Create a directory to hold the global hooks:
mkdir -p ~/.git-templates/hooks
  1. Write your hook in ~/.git-templates/hooks

See file pre-push in this gist.

Copy it to ~/.git-templates/hooks/pre-push

  1. Make it executable
chmod a+x ~/.git-templates/hooks/pre-push
  1. In currently existing project, do reinit

git init

This will not overwrite existing commits, or existing hooks.

Done!

#!/bin/bash
protected_branch='master'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
if [ $protected_branch = $current_branch ]
then
echo -en "\033[31mYou're about to push master, is that what you intended? [y|n] \033[0m"
echo -en "\033[1m"
read -n 1 -r < /dev/tty
echo -en "\033[0m"
echo
if echo $REPLY | grep -E '^[Yy]$' > /dev/null
then
exit 0 # push will execute
fi
exit 1 # push will not execute
else
exit 0 # push will execute
fi
@mosra
Copy link

mosra commented Sep 26, 2024

It's on my fork, not really an array but should be sufficient nevertheless: https://gist.github.com/mosra/19abea23cdf6b82ce891c9410612e7e1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment