Commit-level checkout
By now, you should be very familiar with the commit-level version of git checkout
.
When passed a branch name, it lets you switch between branches.
git checkout hotfix
Internally, all the above command does is move HEAD
to a different branch and
update the working directory to match. Since this has the potential to overwrite
local changes, Git forces you to commit or stash any changes in the working
directory that will be lost during the checkout operation. Unlike git reset
,
git checkout
doesn’t move any branches around.
You can also check out arbitrary commits by passing in the commit reference instead
of a branch. This does the exact same thing as checking out a branch: it moves the
HEAD
reference to the specified commit. For example, the following command will
check out out the grandparent of the current commit:
git checkout HEAD~2
This is useful for quickly inspecting an old version of your project. However,
since there is no branch reference to the current HEAD
, this puts you in a
detached HEAD
state. This can be dangerous if you start adding new commits
because there will be no way to get back to them after you switch to another
branch. For this reason, you should always create a new branch before adding
commits to a detached HEAD
.