Search code examples
gitbranch

Track all remote Git branches as local branches


Tracking a single remote branch as a local branch is straightforward enough.

git checkout --track -b ${branch_name} origin/${branch_name}

Pushing all local branches up to the remote, creating new remote branches as needed is also easy.

git push --all origin

I want to do the reverse. If I have X number of remote branches at a single source:

git branch -r

Output:

branch1
branch2
branch3
.
.
.

Can I create local tracking branches for all those remote branches without needed to manually create each one? Say something like:

git checkout --track -b --all origin

I've googled and read the manuals, but have come up bunk thus far.


Solution

  • Using Bash:

    After Git 1.9.1

    for i in `git branch -a | grep remote | grep -v HEAD | grep -v master`; do git branch --track ${i#remotes/origin/} $i; done
    

    credits: Val Blant, elias, and Hugo

    Before Git 1.9.1

    Note: the following code if used in later versions of Git (>v1.9.1) causes

    1. (bug) All created branches to track master
    2. (annoyance) All created local branch names to be prefixed with origin/
    for remote in `git branch -r `; do git branch --track $remote; done
    

    Update the branches, assuming there are no changes on your local tracking branches:

    for remote in `git branch -r `; do git checkout $remote ; git pull; done
    

    Ignore the ambiguous refname warnings, Git seems to prefer the local branch as it should.