How to make your local repo track all remote branches in Git

Problem:

In Git you can fetch all branches from all remotes with git fetch --all. But this method has one downside: fetch will not create local branches in your local repository for remote tracked branches. You have to do this manually. Hence, we can automate this process by using git alias and bash scripting.

Prerequisites:

Create global git alias track-all-branches

git config --global alias.track-all-branches '!git fetch -p && for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done; git branch -a'

View created alias:

git-alias

Usage:

git track-all-branches

If remote branch was deleted, you can sync your local repo with

git sync

CAUTION: git synccommand is dangerous, as it will delete your local branch. Use this command after git track-all-branches when you are confident that you no longer need the local branch of tracked remote in your repository.

Example output

The output of git track-all-branches will list all local and remote branches and notify if the new branch was added to track. In this example remote repo has a new branch created extras-4:

track-all-brances

Explanation:

  1. git fetch -p - before fetching, removes any remote-tracking references that no longer exist on the remote.
  2. git branch -r - lists all remote tracking branches
  3. git branch --track [remote_branch] - tracks the remote branch