This website recently got a major rebuild; if you're missing something, let Lorna know.

Understanding Tracking Branches in Git



Here's a topic that took me a while to understand in git, and now (I think!) I do, I thought I'd write it all down while I can remember!

Some branches in git (such as your origin/master branch) will usually track the remote branch that they are related to. But what if you want to create a relationship between local and remote branches? Or stop them from tracking? Here's some pointers

What is a tracking branch?

This is a branch which knows which remote branch it is related to, and making this link allows us to take advantage of some neat git tricks. In particular:

  • You can git push or git pull without specifying remote or branch and it will use its tracking sister branch by default
  • The git status command will include information about how far behind your tracking branch you are - useful to remind you that you haven't pushed your changes yet! It looks like this:
$ git status
# On branch branch1
# Your branch is ahead of 'origin/branch1' by 1 commit.
#   (use "git push" to publish your local commits)
#
nothing to commit, working directory clean

Which branches are tracking what?

Let's start with getting a handle on what branches are currently tracking other branches, using git branch -vv

$ git branch -vv
  branch1    c98bacf [origin/branch1] A random change of 24459 to ideas2.txt
  experiment 09a0eb9 A random change of 16603 to list2.txt
* master     09a0eb9 [origin/master] A random change of 16603 to list2.txt

This shows three branches, two of them are tracking branches on another remote. It's common for the branches to have the same names on the various remotes but it's only a convention; you can actually call them anything you like (but beware of getting confused!)

Remove a current tracking relationship

This bit is simple, but rarely documented: git branch --unset-upstream

Which branches get pushed/pulled?

This is an area of confusion because the defaults changed between versions of git. Take a look at your config (use git config --list) and find a setting called push.default. The usual default is simple which will only push/pull the branch to/from the branch you're currently on and the one it tracks. You can optionally set this to be matching (this was once the default) which will then push/pull all changes between all branches and their remote tracking sisters. Sometimes this second option is cumbersome if you have a branch that is not the one you're working on get into a state where it won't merge!

Tracking Branches

Tracking branches are a timesaver once you have them set up correctly, so I hope that this collection of notes helps you to do just that :) Did I miss anything? Leave me a comment!


In: tech
Tags: #git