Reputation: 3250
If I have to undo whatever changes I have done in working branch,
git checkout .
git reset --hard HEAD
both commands will take me to the last commit. What is the difference in both command? And when we should use which command?
Any help will be appreciated. Thanks in advance.
Upvotes: 1
Views: 566
Reputation: 341
git checkout
will only update the working tree, that is changes which have not yet been staged using git add ...
.
git reset --hard HEAD
will both update the working tree and the index (staged files).
The more flexible and transparent option is to use git checkout -p
, which will prompt for each section to undo individually, and won't undo changes which have been staged. This is a great choice for undoing bits of code you don't want, while retaining some working tree changes. It also forces you to look at what you're deleting, reducing the chance of an unrecoverable mistake.
Using reset would be more appropriate when you have a large number of working tree and staged changes that you are absolutely sure you want to undo, such as after an accidental folder deletion or a bad git mv
.
Upvotes: 2
Reputation: 7873
Short version: git checkout
only touches your working copy, but git reset --hard
can change what a branch points to. An example from man git-reset
:
Undo a commit, making it a topic branch
$ git branch topic/wip (1)
$ git reset --hard HEAD~3 (2)
$ git checkout topic/wip (3)
1. You have made some commits, but realize they were premature to
be in the "master" branch. You want to continue polishing them in a
topic branch, so create "topic/wip" branch off of the current HEAD.
2. Rewind the master branch to get rid of those three commits.
3. Switch to "topic/wip" branch and keep working.
In your example they're effectively interchangeable, but if you used something besides HEAD
(as in the example from the man page) you can alter history.
Upvotes: 2