Occasionally, you might need to identify the branches available on a remote repository to pull them down, inspect them, or merge them into your local branches. While platforms like GitHub or gitweb make it easy to discern branch names, it’s less straightforward for general purposes or scripting.

UPDATE: After some enlightening comments, it seems there are multiple approaches to achieve this using Git. The simplest method involves utilizing the various options of the git branch command. The -a flag displays all local and remote branches, while -r shows 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

Once you ascertain the branch names, checking them out is straightforward. Additionally, if you have color options enabled, it’s easy to identify branches that haven’t been pulled down as they’re listed in red.

Another method involves leveraging remote-related commands: git remote and git ls-remote. The former provides comprehensive information about the remote and its relationship with your repository, while the latter simply lists all references to branches and tags it’s aware of.

$ 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 each reference, making it easy to parse and access the exact commit needed, especially for scripting. By using the –heads option, only branch names are listed, excluding tags.

If you have other uses for these commands or an easier method to identify branches on a remote, feel free to share!