Branching with Git – keeping remote and local sync'd

Max pointing me to his method of branching, inspired by: http://www.zorched.net/2008/04/14/start-a-new-branch-on-your-remote-git-repository/

Which creates a branch on the remote origin and then pulls it down and tracks it locally.

The author created a bash script and I wanted to make that a function to keep in my .bashrc file;

#———————————————————–
# Git functions
#———————————————————–
function git-create-branch(){ # git-create-branch
#!/bin/sh
#from http://www.zorched.net/2008/04/14/start-a-new-branch-on-your-remote-git-repository/
if [[ ! -n “$1” ]] ; then
echo 1>&2 Usage: $0 branch_name
else
#$1 -> branch_name
echo “Adding $1”
git push origin master:refs/heads/$1
git fetch origin
git checkout –track -b $1 origin/$1
git pull
echo “#To delete the branch use: git-delete-branch $1”; echo -n;
echo “local branches: “;
git branch
echo “Remote branches: “;
git branch -r
fi
}

function git-delete-branch(){ # git-create-branch
#!/bin/sh
#modified from script at http://www.zorched.net/2008/04/14/start-a-new-branch-on-your-remote-git-repository/
if [[ ! -n “$1” ]] ; then
echo 1>&2 Usage: $0 branch_name
else
#$1 -> branch_name
echo “Removing $1”
git checkout master
git push origin :/heads/$1
git branch -d $1
git fetch origin
git pull origin master
echo “local branches: “;
git branch
echo “Remote branches: “;
git branch -r
fi
}

Usage example:

To add this to your .bashrc

you could edit your .bashrc file

$ vim ~/.bashrc;
:i
[ctrl+v]
:wq
$ source ~/.bashrc

and then test it by creating a branch:

$ git-create-branch mybranch

You know it worked if you don’t see a bunch of warnings. Also you should see both the local and remote branches listed.

then delete it again:

$ git-delete-branch mybranch

Once again you’ll see the local and remote branches listed. ‘mybranch’ should be gone from both unless you made changes locally. In which case the (branch -d) delete command will fail as the branch was not fully merged. It will provide you with instructions for forcing the delete.

Notes about the code:

The ” preceding the git command is there to escape any git aliases. “alias git=agit;” for example (which in a roundabout way is an alias for ‘sudo -u aegir git’. We need to escape that in our home directories.

I make some assumptions that your main branch on the remote host is ‘master’ ie. ‘origin master’. The author of the post appears to have used ‘origin’ ie. ‘origin origin’.

Leave a Comment