Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/bin/bash
# git-offload: a tool for shifting local commits to a new branch and pushing it
# Author: Mikayla Hutchinson <m.j.hutchinson@gmail.com>
if [ "$#" -ne 2 ]; then
echo
echo "Creates new branch from the current commit and pushes it to a remote"
echo "and then resets the original branch to its upstream state."
echo ""
echo "USAGE:"
echo " $(basename $0) remote new-branch"
echo
exit 1
fi
NEWREMOTE=$1
NEWBRANCH=$2
NEWUPSTREAM="$NEWREMOTE/$NEWBRANCH"
BRANCH=$(git branch 2> /dev/null)
if [ "$?" -ne 0 ]; then
echo "not a git repository"
exit 1
fi
BRANCH=$(echo "$BRANCH" | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
UPSTREAM=$(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD))
if [ -z $UPSTREAM ]; then
echo "branch $BRANCH has no upstream configured"
exit 1
fi
CHANGED=$(git diff-index --name-only HEAD --)
if [ ! -z "$CHANGED" ]; then
echo "there are local changes, please commit"
exit 1
fi
echo "$BRANCH $UPSTREAM -> $NEWBRANCH $NEWUPSTREAM"
git checkout -b $NEWBRANCH || exit 1
git push -u $NEWREMOTE $NEWBRANCH || exit 1
git checkout $BRANCH
git reset --hard $UPSTREAM

👍

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