Skip to content

Pushing and Tracking Remote Branches with Git

I write at home and at work, so it is natural for me to use a remote repository to keep track of my work—even with Git. Distributed version control may not force this workflow on you the way subversion does, but the cool thing about Git is that it doesn’t force any particular workflow—it can be adapted to your needs.

The best thing about Git is branching. However, there is a hiccup in pushing a branch to a remote repository that always makes me pause when doing it. So this post is nothing earth shattering. Just a brain dump in the hope that the procedure will become hardwired so that I don’t have to anxiously glance at a man page each time a create a remote branch.

Creating a branch in your local repository is easy enough:

$ git branch <local branch name>

And pushing the branch to the remote repository is easy as well:

$ git push origin <local branch name>

So what’s the problem? The problem is that your local branch isn’t automatically tracking the remote branch. You could edit the git config, but that is a hassle. There is an easier way, though. You can delete the local branch a create a new local branch from the remote one. Fortunately, this can be done in a line:

$ git branch -f <local branch name> origin/<remote branch name>

The key is the -f option—it forces the creation of a new branch even if one of that name already exists. And the second argument specifies the remote branch from which the local branch is created. Creating a new local branch in this way causes it to automatically track the remote branch, so that you can, for example, use git pull without further arguments.

{ 1 } Comments

  1. PO8 | September 30, 2008 at 6:34 am | Permalink

    Nice micro-tutorial! Thanks much, it really helped me out.

    One note: Git won’t let you rewrite the branch you’re currently sitting on. So before you force the new branch, push any changes up to the remote explicitly and then “git checkout master” to get out of the way. After you’ve created the revised branch, “git checkout ” to get back…

{ 1 } Trackback

  1. […] my opinion, Mark Eli Kalderon’s post explains the simplest and most elegant approach. Here is his approach, slightly […]

Post a Comment

You must be logged in to post a comment.
FireStats icon Powered by FireStats