撤銷 git commit --amend

想必你們都知道 git commit --amend 這條實用命令, 其能夠用來修改最後一條提交的 commit message, 也能夠追加新的修改.
但有時候不當心 amend 了錯誤的內容, 如何回退呢?
普通青年通常會用 git reset 撤銷到上一個提交, 再從新 git commit 一次, 這當然是能夠的. 但若是工做區此時已經改的面目全非, 這時若是執行 git reset, 就很難分的清哪些內容屬於被撤銷的提交了. 嗯, 這位同窗說這種狀況能夠用 git stash 來處理, 是能夠解決問題的.
可是, 身爲文藝青年, 怎麼能用這麼不優(zhuang)雅(bi)的方法呢.html

先上結論:
若是隻 amend 了一次, 那麼直接用 git reset HEAD@{1} 就能夠撤銷此次 amend. 若是 amend 屢次, 就參考 git reflog 進行撤銷.git

下面以實例介紹如何就地撤銷 git commit --amend.bash

製造事故現場

首先製造事故現場. 追加空行到項目中的 index.html 文件下:ssh

$ echo "" >> index.html 
$ git add .
$ git commit -m "add blank line to index.html"

而後再加一行到 index.html, 並 amend 一下:this

$ echo "this line would break the code" >> index.html 
$ git add .
$ git commit --amend

現場已經出現, 咱們要撤銷 amend 的那個提交.code

撤銷 amend

首先使用 git reflog 命令查看操做記錄:htm

$ git reflog
c1c1b21 HEAD@{0}: commit (amend): add blank line to index.html
9ff821d HEAD@{1}: commit: add blank line to index.html
b078331 HEAD@{2}: commit: no more commit!
b86e902 HEAD@{3}: commit: so many commit
77e6ce9 HEAD@{4}: commit: this is another commit
ccde039 HEAD@{5}: commit: this is a commit
a49dcf4 HEAD@{6}: clone: from ssh://liux@xxx.xx.xx.xxx:29418/git_test.git

看到 amend 操做以前的最後一個操做就是 HEAD@{1}.
如今能夠用 git reset 將當前分支的 HEAD 指向 HEAD@{1}, 便可達到撤銷 amend 的目的:get

$ git reset --soft HEAD@{1}
$ git status
On branch master
Your branch is ahead of 'origin/master' by 5 commits.
  (use "git push" to publish your local commits)
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   index.html

隨即便用 git status 查看狀態, 發現 amend 的內容已經被撤銷 (到工做區) 了.
若是想撤銷到暫存區, 就用 git reset --soft HEAD@{1} .
若是想幹掉這個修改, 就用 git reset --hard HEAD@{1} .
這和 git reset 操做 commit 的情形是同樣的.it

若是一個 commit 被 amend 了屢次, 也能夠用這種方法撤銷到任意一次 amend 處:ast

$ git reflog
937fd53 HEAD@{0}: commit (amend): add blank line to index.html
7589755 HEAD@{1}: commit (amend): add blank line to index.html
f7ade82 HEAD@{2}: commit (amend): add blank line to index.html
c1c1b21 HEAD@{3}: commit (amend): add blank line to index.html
9ff821d HEAD@{4}: commit: add blank line to index.html
$ git reset --soft HEAD@{2}

能夠看出, 不止是 amend 操做, 其餘操做也能夠用這種方法進行撤銷.

參考:

查看分支操做記錄: git reflog
重置當前分支 HEAD: git reset
相關文章
相關標籤/搜索