File-level checkout
Checking out a file is similar to using git reset
with a file path, except it
updates the working directory instead of the stage. Unlike the commit-level
version of this command, this does not move the HEAD
reference, which means that
you won’t switch branches.
For example, the following command makes foo.py
in the working directory match
the one from the 2nd-to-last commit:
git checkout HEAD~2 foo.py
Just like the commit-level invocation of git checkout
, this can be used to
inspect old versions of a project — but the scope is limited to the specified file.
If you stage and commit the checked-out file, this has the effect of “reverting”
to the old version of that file. Note that this removes all of the subsequent
changes to the file, whereas the git revert
command undoes only the changes
introduced by the specified commit.
Like git reset
, this is commonly used with HEAD
as the commit reference. For
instance, git checkout HEAD foo.py
has the effect of discarding unstaged changes
to foo.py
. This is similar behavior to git reset HEAD --hard
, but it operates
only on the specified file.