Introduction

The git checkout command switches between branches or restores working tree files. This command operates upon three distinct entities: files, commits, and branches. Checking out branches is similar to checking out old commits and files in that the working directory is updated to match the selected branch/revision. However, new changes are saved in the project history.

Checking out branch

Use git checkout command to navigate between the branches created by git branch. Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch. Difference between git clone and  git checkout is that clone works to fetch code from a remote repository, while checkout works to switch between versions of code already on the local system.

In order to checkout a remote branch you have to first fetch the contents of the branch, then checkout the remote branch like a local branch.

# Checkout an existing branch
git checkout <BRANCH-NAME>

# Checkout remote branch
git fetch --all
git checkout <REMOTE-BRANCH-NAME>

Creating new branch

git branch command can be used to create a new branch using ‘master’. Once created you can then use git checkout new_branch to switch to that branch. Alternatively git checkout command accepts a -b argument, which will create the new branch and immediately switch to it. By default git checkout -b will base the new-branch off the current HEAD. To base the new branch from existing branch, an optional additional branch parameter can be passed to git checkout.

# Create and checkout out a new branch from current head
git checkout -b <NEW-BRANCH-NAME>

# Create and checkout out a new branch from 'OLD-BRANCH-NAME'
git checkout -b <NEW-BRANCH-NAME> <OLD-BRANCH-NAME>

Checkout specific commit

To go back to earlier revisions, use git log to find the commit id and use git checkout to move the branch to that commit.

# Get the specific commit id
git log

# Checkout a specific commit
git checkout specific-commit-id

Force checkout

To force checkout to a branch, use -f or --force option with the git checkout command. This will leave the current branch even if there are un-staged changes (in other words, the index of the working tree differs from HEAD). Basically, it can be used to throw away local changes.

git checkout -f BRANCH-NAME

Undo Changes

git checkout can also undo changes you’ve made to file(s) in your working directory i.e. revert un-staged files. This will revert the file back to the version in HEAD.

git checkout -- FILE-NAME