When exploring branching in Git, you’ve probably come across the term tracking branch. Or even if you are new to the concept of branching, working with a remote repository should have already exposed you to a tracking branch even if you are not aware.
A tracking branch is a local branch with a direct relationship to a remote branch.
Many developers just refer to tracking branches as local branches.
When we clone a remote repo, the local master branch is automatically setup as a tracking branch for the remote origin/master branch. When a tracking branch is in place, running
git status will show you whether your local branch (master) is in-sync with your remote branch (origin/master)
Setting up tracking branches
By default, only the remote master branch is visible when we run the
git branch command. To view all branches, we need to include the -a flag like so:
git branch -a
As seen in the above image, our remote repo contains two branches: 1) master and 2) new-feature.
Since the master branch is already being tracked, we would need to manually setup a tracking branch for origin/new-feature. And here are a few ways to do that:
git checkout -b new-feature origin/new-feature
This is almost the same way as creating a new branch except we need to add the name of the remote branch (origin/new-feature) after the local branch (new-feature). Also, this allows you to specify a remote branch name that is different from the tracking branch name.
git checkout —track origin/new-feature
But most of the time, to avoid confusion, we would want the remote and tracking branch to have the same name. And this shortcut does just that.
git checkout my-new-branch
Finally, to accommodate to us lazy developers, this is an even shorter and probably the most common method to setup a tracking branch. Basically, it tells Git to check if there is a remote branch called ‘my-feature’. It will then create a tracking branch with the same name and set it up to track the remote branch.
Now that we have our tracking branches setup, we can start to commit and push changes to our remote branches or pull updates into our local branches.