Let's say I want to undo all changes introduced by previous commits.
As far as I understand, git reset --hard <specified commit>
will remove all commits up until the specified commit, and undo all changes.
On the other hand git checkout <specified commit>
will change my directory to reflect the specified commit.
So if I git reset
after git checkout
will it have the same result as git reset --hard
?
Alternatively, if I simply git commit
after git checkout
, will the newly created commit overwrite the existing commits?
In a nutshell, git commits are a tree, and branches are just pointers to some commits.
git checkout <specified commit>
does not move the branch pointer. When you do this, you are in detached head state. You will see this message, which is pretty self-explanatory:
You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
Another difference is that git checkout
is safer, because it will not reject your changes in the working tree, and you will not lose any commits with it¹.
git reset --hard <specified commit>
, on the other hand, will move your current branch to the specified commit and you will lose all the changes in your working tree. Additionally, if you're moving to some older commit, and the newer commits are not in some other branch, you will lose these newer commits too. It is not a safe operation and don't do this unless you really understand what you're doing.
See also these great answers for information about how to undo a git commit.
You might also benefit from using a GUI tool like SourceTree.
¹ - well, unless you're already in detached head state on some dangling commit, but normally you shouldn't worry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With