git reset
把当前branch
的HEAD
恢复到之前某个snapshot
。举例如下:
假设当前repository
分三次添加a
,b
,c
文件:
[root@localhost test_git]# git log --oneline
e5b4692 Add c
be89e2d Add b
80c615e Add a
执行git reset --hard HEAD~1
命令,HEAD~1
表示当前HEAD
之前的第一个commit
:
[root@localhost test_git]# git reset --hard HEAD~1
HEAD is now at be89e2d Add b
[root@localhost test_git]# git status
On branch master
nothing to commit, working directory clean
[root@localhost test_git]# git log --oneline
be89e2d Add b
80c615e Add a
[root@localhost test_git]# ls
a b
可以看到git log
中已经找不到添加c
文件的log
。而c
文件也不存在了。
如果执行git reset --mixed HEAD~1
命令,则虽然repository
已经回滚到HEAD
之前的第一个commit
,但c
文件还会存在:
[root@localhost test_git]# git reset --mixed HEAD~1
[root@localhost test_git]# git log --oneline
be89e2d Add b
80c615e Add a
[root@localhost test_git]# ls
a b c
恢复之前HEAD
状态,可以利用git reflog
找到相应的commit
,然后创建一个新的branch
,最后merge
回master
:
[root@localhost test_git]# git reflog
be89e2d HEAD@{0}: reset: moving to HEAD~1
deb862b HEAD@{1}: commit: Add c
be89e2d HEAD@{2}: reset: moving to HEAD~1
e5b4692 HEAD@{3}: commit: Add c
be89e2d HEAD@{4}: commit: Add b
80c615e HEAD@{5}: commit (initial): Add a
[root@localhost test_git]# git checkout deb862b
Note: checking out 'deb862b'.
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>
HEAD is now at deb862b... Add c
[root@localhost test_git]# git log --oneline
deb862b Add c
be89e2d Add b
80c615e Add a
[root@localhost test_git]# git branch
* (HEAD detached at deb862b)
master
[root@localhost test_git]# git checkout -b temp
Switched to a new branch 'temp'
[root@localhost test_git]# git branch
master
* temp
[root@localhost test_git]# git checkout master
Switched to branch 'master'
[root@localhost test_git]# git merge temp
Updating be89e2d..deb862b
Fast-forward
c | 0
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 c
[root@localhost test_git]# ls
a b c