The three Git commands reset, revert, and checkout can be somewhat confusing, since all appear to perform similar operations. Another reason these three commands can be confusing is that other version control systems have different meanings for the words reset, revert, and checkout.
However, there are some good guidelines and rules for when each command should and should not be used.
If you want to change to a different branch, use git
checkout. Your current branch and HEAD
ref
change to match the tip of the given branch.
The git reset command does not change your
branch. However, if you supply the name of a branch, it will change the
state of your current working directory to look
like the tip of the named branch. In other words, git
reset is intended to reset the current branch’s
HEAD
reference.
Because git reset --hard is designed to recover to a known state, it is also capable of clearing out failed or stale merge efforts, whereas git checkout will not. Thus, if there were a pending merge commit and you attempted to recover using git checkout instead of git reset --hard, your next commit would erroneously be a merge commit!
The confusion with git checkout is due to its
additional ability to extract a file from the object store and put it
into your working directory, possibly replacing a version in your
working directory in the process. Sometimes the version of that file is
one corresponding to the current HEAD
version, and
sometimes it is an earlier version.
# Checkout file.c from index $git checkout -- path/to/file.c
# Checkout file.c from rev v2.3 $git checkout v2.3 -- some/file.c
Git calls this “checking out a path.”
In the former case, obtaining the current version from the object
store appears to be a form of a “reset” operation—that is,
your local working directory edits of the file are discarded because the
file is “reset” to its current, HEAD
version. That is double-plus ungood Git thinking.
In the latter case, an earlier version of the file is pulled out of the object store and placed into your working directory. This has the appearance of being a “revert” operation on the file. That too is double-plus ungood Git thinking.
In both cases, it is improper to think of the operation as a Git
reset or a revert. In both cases, the file is “checked out”
from a particular commit: HEAD
and
v2.3
, respectively.
The git revert command works on full commits, not on files.
If another developer has cloned your repository or fetched some of your commits, there are implications for changing the commit history. In this case, you probably should not use commands that alter history within your repository. Instead, use git revert; do not use git reset nor the git commit --amend command described in the next section.
3.147.67.195