Git - Jump between branches using Git Checkout

This article covers how to use the command 'Git Checkout'

Git checkout of the most frequently used commands in git, allowing us to jump from one branch to another. Currently on the master branch, but need to test the code in staging? You need to use git checkout:

git checkout <branch-name>

Alternatively, you can simultaneously create and checkout a new branch by adding the -b flag:

git checkout -b <branch-name>

You may have issues checking out a new branch if you already have changes in your current branch, in which case you have three options:

  • Commit the changes to the branch before continuing
  • Stash the changes
  • Add the --force (-f) flag, which will ignore any local changes that haven't been staged (use with caution!)

Typically, I'll find myself working on the wrong branch, in which case stashing my changes and checking out the correct branch, before re-applying the stash resolves my issue.

If you wish to revert your local changes on a single file, you can also use git checkout, with the file name:

git checkout -- <file-name>

This should also be used with caution! Git will replace the file with the remote version, wiping out all local changes. You should only use this is you're sure you don't want those unsaved changes.