Let’s take a look at the main purpose of and common uses for the git checkout command.

First, here is a quick summary of the whole article (if you get the summary, reading the rest is optional):

# checkout out a branch (i.e. make working directory look like the
# latest commit in that branch)
git checkout <branch>

# replace a file in the working directory with the version of the file
# in another commit
git checkout <from commit> someFile.txt

# replace a file in the working directory with the version of the file
# in the index (i.e. remove local changes to file)
# notice: you basically leave out the commit identifier
git checkout someFile.txt

# if you have a merge conflict, choose your version of a certain file
git checkout --ours someFile.txt

# NOTE: In any of the above examples, you can use globs to select
# multiple files, so for example, to revert all .cpp files:
git checkout *.cpp


# Overarching purpose

The overarching purpose of git checkout is to modify files in your working directory.

# Common uses

There are two common uses for git checkout:

1. To switch branches.
2. To replace certain files in the working directory with files from:
• another commit
• the index
• a certain party during a merge conflict

## Switch branches

To switch branches, just do:

git checkout <name of branch>


This will make your working directory look like the specified branch and makes HEAD point to the latest commit in the new branch (recall HEAD is basically a pointer to the commit that you have checked out).

## Replace a file in the working directory

To replace fileA.ext in the working directory with fileA.ext from a specific commit, do:

git checkout ca82a6dff8 fileA.ext


The long word with the random letters and numbers is the hash of the commit from which you want to grab fileA.ext from.

To replace a bunch of files, use globs (e.g. *.cpp to replace all .cpp files).

git checkout ca82a6dff8 *.cpp


To grab the file from the index instead of a specific commit, just leave out the commit hash:

git checkout fileA.ext


Grabbing the file from the index basically reverts the local changes on the file. Of course, you know what the index is right? Yup that’s right! It’s basically the commit you last checked out (so the current branch) plus any modifications that you added to the staging area.

If you have attempted a merge and there are merge conflicts, you can pick certain files in the working directory to be ours or theirs.

This will choose our version of the conflicted file fileA.ext:

git checkout --ours fileA.ext


And this will choose theirs:

git checkout --theirs fileA.ext


## Bonus

As a bonus (since I’m a nice young man and I like to give out free stuff :P), if you quickly want to create a new branch stemming from your current commit (branch) and then checkout (i.e. switch to) the new branch, do:

git checkout -b <name of new branch>