Skip to content

Instantly share code, notes, and snippets.

@ben-cohen
Last active December 12, 2017 14:01
Show Gist options
  • Save ben-cohen/316f89c763e9d8a027335261a44c4954 to your computer and use it in GitHub Desktop.
Save ben-cohen/316f89c763e9d8a027335261a44c4954 to your computer and use it in GitHub Desktop.
Git post-commit hook to create a branch automatically when commiting from a detached HEAD
#!/bin/sh
#
# Git post-commit hook to create a branch automatically when commiting from a
# detached HEAD.
#
# Install in your repo as .git/hooks/post-commit and make it executable.
#
# Ben Cohen, December 2017.
set -e
BRANCH=`git rev-parse --abbrev-ref HEAD`
if [ "$BRANCH" = "HEAD" \
-a ! -e "$GIT_DIR/rebase-apply" \
-a ! -e "$GIT_DIR/rebase-merge" ]
then
# Detached HEAD and this is not a rebase
COMMIT=`git rev-parse --verify --short HEAD`
BNAME=`date +"DH-%Y-%m-%d-$COMMIT"`
echo "Commit on detached HEAD: creating branch $BNAME."
echo '(Use "branch -m <newbranch>" to rename it.)'
echo
git checkout -b $BNAME
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment