Compare about using checkout or reset hard to undo git commit
If I use:
$ git checkout HEAD~N
Both of two will use the version of
HEAD~N to change working directory and stage area.
If there is any different between these two commands?
3 Solutions collect form web for “Compare about using checkout or reset hard to undo git commit”
git checkout HEAD~N is meant to examine the commit and not to be worked on as it will create a detached head state. If you want to reset (the current branch head) to a particular commit, you use
git reset [--hard]
git reset --hardwill reset the current branch HEAD to the specified refspec
git checkoutwill switch branch, and leave you in a detached head mode.
So with the first, you can start committing right away, in your current branch.
With the second, you need to define a branch first, you (previously) current branch HEAD hasn’t move. Only the working directory has been changed. And you are no longer in any branch (hence the “detached mode”).
The first will change the branch to point to the commit that you specify. The commits that were ahead of that one will be lost unless there is another reference to them (branch or tag). There is the reflog (git reflog) that keeps a history of what was checked out (by default this keeps the last 90 day’s worth)
The second will switch the branch to what you specified. Since you specified a commit and not a local branch, you will not be tracking any changes you commit here. Except for the reflog, you will lose these commits that were made subsequent to the first checkout when you do a subsequent checkout other than the current commit or HEAD.
A third way that you can “undo” work is by placing ” — .” after your second command. This will change your working tree to the state that the files are in on the commit you specified. You will still have the same branch checked out and it will still point to the same commit. When you run “git status”, you will see that all the changes in your working dir will look like you edited your files to look like what they were in the commit you specified. Committing these changes will make a new commit that effectively “undoes” what the subsequent commits ahead if the one specified did. Your current branch will now point to this commit. This is a good practice if others may be depending on the commits that you effectively want erased.