git的撤销操作:reset、checkout和revert

概述

这三个命令都可以用于撤销。

reset和checkout可以作用于commit或者文件,revert只能作用于commit。

commit级别的操作

reset

$ git checkout hotfix
$ git reset HEAD~2

git reset用于撤销未被提交到remote的改动,即撤销local的修改。除了移动当前分支的HEAD,还可以更改workspace和index:

  • --soft:修改HEAD,不修改index和workspace。

  • --mixed:修改HEAD和index,不修改workspace。默认行为。

  • --hard:修改HEAD、index、workspace。

git reset --mixed HEAD把index的内容退回到workspace中。
git reset --hard HEAD把index和workspace的修改全部撤销。

checkout

checkout作用于commit级别时,只是移动HEAD到不同的commit。如果有unstaged的文件,git会阻止操作并提示。如果使用commit id作为参数,可能会导致野指针。

revert

$ git checkout hotfix
$ git revert HEAD^^

revert通过新建一个commit来撤销一次commit所做的修改,是一种安全的方式,并没有修改commit history。

revert用于撤销committed changes,reset用于撤销uncommitted changes。

file级别的操作

reset

git reset <commit> <filename>只修改index去匹配某次commit。

git reset HEAD filename把文件从index退回workspace,并将更改保存在workspace中。

checkout

git checkout <commit> <filename>只修改workspace去匹配某次commit。

git checkout HEAD filename抹掉文件在workspace的修改。

总结

CommandScopeCommon use cases
git resetCommit-levelDiscard commits in a private branch or throw away uncommited changes
git resetFile-levelUnstage a file
git checkoutCommit-levelSwitch between branches or inspect old snapshots
git checkoutFile-levelDiscard changes in the working directory
git revertCommit-levelUndo commits in a public branch
git revertFile-level(N/A)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值