Git中取消操作的方法

使用git revert命令取消已经committed的操作。举例如下:

[root@localhost git_repo]# git log --oneline
4a95041 Add a crazzzy experiment
5f08b5f Add navigation links
7f9fa70 Create blue and orange pages
7807520 Commit the first version of index.html.

如果想取消最后一次commitcommit ID4a95041),使用git revert 4a95041命令:

[root@localhost git_repo]# git revert 4a95041
[master 0b959a0] Revert "Add a crazzzy experiment"
 Committer: root <root@localhost.localdomain>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly. Run the
following command and follow the instructions in your editor to edit
your configuration file:

    git config --global --edit

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 1 file changed, 14 deletions(-)
 delete mode 100644 crazy.html
[root@localhost git_repo]# git log --oneline
0b959a0 Revert "Add a crazzzy experiment"
4a95041 Add a crazzzy experiment
5f08b5f Add navigation links
7f9fa70 Create blue and orange pages
7807520 Commit the first version of index.html.

现在第三次和第五次commit代表相同的snapshot。并且第四次commit还在revision history中,以后也可以恢复到第四次commit的内容。要注意,git revert命令使用的commit ID是要取消操作的commit ID,不是要“回滚”到的commit ID

取消还没committed的操作分以下两种情况:

(1)Tracked文件:git reset --hard命令会把所有tracked文件恢复到最近一次committed状态。加上--hard选项会真正更新文件,否则只是unstage文件,但文件的内容还是变化了。

(2)Untracked文件:git clean -f会删除所有untracked文件。

git reset取消working directorystaged snapshot的操作,而git revert是取消committed snapshots的操作。如下图所示:

2-5

参考资料:
Undoing Changes

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.