A local git branch can track a remote branch, which means that git push and git pull commands will know to push and pull commits to and from the tracked branch by default. Also git status will tell the status between your current local branch and the remote branch it's tracking. When you clone a git repository, git will add a tracking reference to the local master branch to track the remote master branch. When you checkout from a new remote branch, git will add a tracking reference to the created local branch to track the remote branch you checked out.
However, if you create a new branch locally, and then push it to the remote repository, you have to explicitly tell git if you want your local branch to start tracking the new remote branch. You do that with the -u
or --set-upstream
option when pushing the local branch to the remote repository: git push -u origin my-new-branch
.
You can check which remote branches your local branches are tracking (if any) with the command git branch -vv
Below is a small example of the output.
b1 560eb64 Added file.txt
b2 560eb64 [origin/b2] Added file.txt
b3 b638c18 [origin/r1: ahead 1] Added file3.txt
* master 560eb64 [origin/master] Added file.txt
In this case we have local branches master
, b1
, b2
and b3
. The master
branch is tracking a remote branch called master
, the b1
branch isn't tracking any remote branches, the b2
branch is tracking a remote branch called b2
and the b3
branch is tracking a remote branch called r1
. git branch -vv
also shows the status of the branch related to the traced branch. Here branch b3
is 1 commit ahead of the tracked remote branch and the other branches are up to date with their respective remote tracked branches.
So if you create a local branch and push to the remote repository, would you want to add a tracking reference to the branch or not? Usually when you push a new local branch to the remote repository, you do it to collaborate with other developers on a feature. If you add a tracking reference to your local branch, you can conveniently pull the changes that other people have made to the branch, so I would say that in most cases you want to add the tracking reference.