What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

I tried to undo my commit in git. Is it dangerous to use git reset --hard HEAD~1?

What is the difference between different options for git reset?

Is there also any other way to undo a commit by Sourcetree Gui?

回答1:

git reset does know five "modes": soft, mixed, hard, merge and keep. I will discuss the first three, since those are the ones you usually use.

soft

When using git reset --soft HEAD~1 you will undo the last commit, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit will create a commit with the exact same changes as the commit you "removed" before.

mixed

This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1 you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add) before commiting.

hard

When using git reset --hard HEAD~1 you will lose the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status command will tell you that you don't have any changes in your repository.


You can read more about that in the git reset documentation.

Note
When doing git reset to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a "deleted" commit with git reset, for example by using git reflog or similar commands to find it's SHA-1 key.



回答2:

This is a useful article which graphically shows the explanation of the reset command.

http://git-scm.com/blog/2011/07/11/reset.html

Reset --hard can be quite dangerous as it overwrites your working copy without checking, so if you haven't commited the file at all, it is gone.

As for Source tree, there is no way I know of to undo commits. It would most likely use reset under the covers anyway



回答3:

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!