git list remote branches

Sometimes you may need to figure out what branches exist on a remote repository so you can pull them down and check them out, merge them into your local branches, etc. If you’re using GitHub or gitweb to host your repository it’s usually easy to determine the branch names, but if you need to get them in general or for scripts it’s not exactly clear.

UPDATE: The comments have enlightened me quite a bit…there seems to always be more than one way to skin a cat using Git. The easiest way is just to use the git branch commands’ various options. -a shows all local and remote branches, while -rshows only remote branches.

$ git branch
* master

$ git branch -a
* master
  origin/1-2-stable
  origin/2-0-stable
  origin/2-1-stable
  origin/2-2-stable
  origin/3-0-unstable
  origin/HEAD
  origin/master

$ git branch -r
  origin/1-2-stable
  origin/2-0-stable
  origin/2-1-stable
  origin/2-2-stable
  origin/3-0-unstable
  origin/HEAD
  origin/master

So, once you know the name of the branch it’s quite simple to check them out. If you have color options on it’s also quite easy to tell which branches aren’t pulled down since they’re listed in red.

There’s also another way to do figure out what branches are on your remote by actually using the remote related commands, git remote and git ls-remote. The former displays plenty of information about the remote in general and how it relates to your own repository, while the latter simply lists all references to branches and tags that it knows about.

$ git remote show origin
* remote origin
  URL: git://github.com/rails/rails.git
  Remote branch merged with 'git pull' while on branch master
    master
  Tracked remote branches
    1-2-stable 2-0-stable 2-1-stable 2-2-stable 3-0-unstable master

$ git ls-remote --heads origin
5b3f7563ae1b4a7160fda7fe34240d40c5777dcd  refs/heads/1-2-stable
71926912a127da29530520d435c83c48778ac2b2  refs/heads/2-0-stable
2b158543247a150e8ec568becf360e7376f8ab84  refs/heads/2-1-stable
b0792a3e7be88e3060af19bab01cd3d26d347e4c  refs/heads/2-2-stable
d6b9f8410c990b3d68d1970f1461a1d385d098d7  refs/heads/3-0-unstable
f04346d8b999476113d5e5a30661e07899e3ff80  refs/heads/master

The ls-remote command returns the SHA1 hash of the latest commit for that reference, so it is quite easy to parse out and get to the exact commit you need if you’re doing some scripting. The --heads option lists only branch names since the command can list tags too.

If you have any other uses for these commands or an easier way to figure out branches that live on a remote, comment away!

Source: http://gitready.com/intermediate/2009/02/13/list-remote-branches.html

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

粤ICP备15062915号-1