git commit回滾

從svn 遷移到 git,已經(jīng)有很長時間。git 的基本命令已經(jīng)可以說是熟練的掌握,能夠滿足日常的開發(fā)。想了解常用git命令可以查看: 常用git命令

但是也有一些不常用,但在關(guān)鍵時刻又非常有用的命令,這里就介紹一種:撤銷已經(jīng)提交的commit

1. 應(yīng)用場景 :

撤銷已經(jīng)提交的commit

2. 解決方案:

  1. 使用 git reset --hard HEAD^

  2. 使用 git rebase -i HEAD~n

下面分別介紹下這兩個方案有什么不同,和他們的使用場景 。

2.1 git reset --hard 丟棄最新的提交

代碼提交后,需求發(fā)生變化導(dǎo)致之前提交的已經(jīng)不合適,或者 代碼提交后發(fā)現(xiàn)有嚴重bug,需要回滾可是使用這個命令:

git reset --hard HEAD^

tips:

1,HEAD^   表示 最新提交HEAD位置往回數(shù)一個提交, 幾個 ^  就往回數(shù)幾個提交;

2,HEAD~n  表示 新提交HEAD位置往回數(shù)n個提交

可以發(fā)現(xiàn),reset 命令只能回滾最新的提交。

如果最后一次commit需要保留,而只想回滾之前的某次commit,reset命令可能就無法滿足了。(這個場景我第一次遇到的時候很是抓瞎)

2.2 git rebase -i 丟棄指定提交

針對想撤銷中間某次commit的情況,可以使用如下的命令:

git rebase -i HEAD~2

tips:

1, `rebase -i`是 `rebase --interactive` 的縮寫;
2,  `git rebase -i` 不僅可以刪除commit, 還可以修改commit。 具體的可以查看rebase 中提示的參數(shù)

輸入git rebase -i HEAD~2命令后,會出現(xiàn)一個編輯頁面如下:

$ git rebase -i HEAD~2

drop e47fa58 提交11
pick 338955c 提交12

# Rebase 7f83da3..338955c onto 7f83da3 (2 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
~      

編輯界面能夠執(zhí)行的操作,都有羅列出來:

`edit: 使用本次提交,在rebase到這次提交時候,會暫停下來等待修正`
`pick:使用本次提交,不操作修改`
`drop:刪除這次提交`
`...`

這里的目標是刪除倒數(shù)第二個提交,所以將倒數(shù)第二個提交前面修改為drop, 然后退出編輯界面就可以了。

再通過 git log 查看提交歷史的時候,就會發(fā)現(xiàn)e47fa58 的提交記錄已經(jīng)不見了。

總結(jié):

  1. 回滾最新的提交 :git resetgit rebase 命令都可以
  2. 回滾中間某次提交: git rebase 可以, git reset 不可以
  3. 如果提交已經(jīng)同步到遠程倉庫,需要使用git push origin -f branch(分支名) 來將回滾也同步到遠程倉庫(master 分支謹慎使用 -f)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容