Farid Farid - 1 year ago 97
Git Question

Update all local branches with all remote branches

How do I override all local branches with all remote branches?

Here are my local branches:

client-side-js-framework
client-side-js-framework-2
client-side-js-framework-3
handlebars
master


And my remote branches:

client-side-js-framework
handlebars
master
no-network-connection


I want my local branches to mirror my remote branches as my remote branches are more up to date. In other words, my local branches should be:

client-side-js-framework
handlebars
master
no-network-connection


Can this be done with one (or two) commands, rather than basically deleting my local repo, and re cloning it?

Answer Source

Most likely, you should run:

git fetch origin

and then simply delete (most or all of) the local branches. The next time you run, e.g.:

git checkout handlebars

your Git will search for your local name handlebars, fail to find it, search some more to see if there's exactly one name like origin/handlebars and upstream/handlebars and so on (one for each possible remote).

As long as there's exactly one such name, your Git will then say: Aha, I should create local name handlebars using the same commit as remote-tracking name origin/handlebars. In that instant you will get a local branch named handlebars that matches origin/handlebars, Git will check it out, and you will be ready to work. There's no need to drag half a dozen not-being-worked-on local names around like a set of balls-and-chains.

If you really do need each branch updated, you must use a loop, with one update command per branch to do an appropriate merge and push, unless they're all fast-forward not-really-a-merge operations, in which case:

git fetch origin 'refs/heads/*:refs/heads/*'

will work—but don't do it (see the ball and chain link).

(It's a little trickier if you do have multiple remotes that use the same names. In this case, git checkout --track origin/handlebars will achieve the desired result. Meanwhile it's also tricky, and unwise, to let git fetch delete local names, but I think it can be done with --prune.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download