Ever wondered if there was a quick guide to working with branches. Sure there’s Git SCM and Git Ref, but it’s not always obvious what that one line of code is that you need, right now!. So here’s my attempt to address the issue. For those familiar with git, but don’t quite know what command to run.

This is a list of git commands for common situations when working with branches. It addresses branch creation, discovery and syncronization.

  • git branch : Lists your current branch.
  • git branch -a : List all local and remote-tracking branches. A remote-tracking branch is a remote branch you have linked to a local branch so can pull and push. This will also show remotes for which the local branch has been deleted. This command will NOT show branches that have not been tracked, like any new branches on ‘origin’.
  • git ls-remote --heads origin : List all branches on ‘origin‘ server. This includes branches that are not being tracked on your system. Use this to find a new remote branch.
  • git ls-remote --heads . : List all remote branches being tracked on your system. This is less useful than git branch -a.
  • git fetch --all : Fetch all remote branches and tags. For small private projects it’s worth doing this every now and then, just to see what features are in development. On a large public repo this can be overkill.
  • git checkout --track origin/sitev2 : Create a new local branch called ‘sitev2’ that tracks to an existing remote branch ‘origin/sitev2’. Do this when you want to contribute to an already existing remote branch. To use this command you must first run git fetch origin, so you can see the remote branch on your system.
  • git branch newfeature : Creates a new local branch called ‘newfeature’, that is untracked until you ‘git push’. Running this command will not switch your branch.
  • git checkout newfeature : Switch to local branch ‘newfeature’. Errors out if the branch doesn’t exist.
  • git checkout -b newfeature : This combines the previous 2 steps. Create a new local branch and switch to it. After you’ve made a commit you can create a new branch on remote using git push -u origin newfeature.
  • git remote show origin : Show local branches, remote branches, which branches are being tracked and to what. This is a good command to get a summary of your git repo. It even shows you old branches you should have pruned. However, it does NOT show local branches that are not tracking remotely.

One thought on “Git Branches

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s