Thursday, February 03, 2011

Creating a locally tracked remote branch with Git

Updated May 30, 2013

Git is a distributed source code control system that allows you to clone a remote repository locally, make commits to it on your machine, and then push them to the remote repository when done.

It is often useful to create a remote branch for features that are experimental or will not be going out in the upcoming release as that allows you to work in isolation of the main code repository changes, thus not get blocked.

In order to work with a Git remote branch, it has to be cloned locally, and there are multiple ways of doing it with different levels of complexity. Some have you create the local branch first. Others have you create the remote branch first.

My intention for this blog post is to document the easiest way to date for creating a remote branch that is tracked locally.

Here it goes (assuming origin is the default):

git branch new_branch_name
git push -u origin new_branch_name


Then you can checkout the local branch and work with it by typing:

git checkout new_branch_name


The local branch automatically tracks the remote branch, so you do not have to worry about explicitly setting that up.

Now, if you already have a remote branch created by someone else though, and you want to check it out locally, you can just run this command (assuming remote is origin):
git checkout -t -b branch_name origin/branch_name

Update: A shorter alternative:

git checkout -t origin/branch_name


A Google search turns out a dozen ways, many of which are over-complicated or out-dated, so I hope people find this blog post helpful for providing the simplest approach to date.

3 comments:

Unknown said...

Hey Andy,

Have you seen the git remote branch gem? http://grb.rubyforge.org/

Makes life easy for working with remote branches. I'm no git expert, so this really helped me.

Anonymous said...

$ git push origin local_branch:remote_branch
$ git branch --set-upstream local_branch origin/remote_branch

The last command only works with git >= 1.7.0 (although you should update git if it's older than that)

Rodolfo Carvajal said...

Thanks for the info!
Just in case, this: http://stackoverflow.com/questions/945654/git-checkout-on-a-remote-branch-does-not-work could be useful if you get a "fatal: git checkout: updating paths is incompatible with switching branches" when trying to checkout a remote branch.