想必大家都知道 git commit --amend 這條實用命令, 其可以用來修改最后一條提交的 commit message, 也可以追加新的修改.
但有時候不小心 amend 了錯誤的內容, 如何回退呢?
普通青年一般會用 git reset 撤銷到上一個提交, 再重新 git commit 一次, 這固然是可以的. 但如果工作區(qū)此時已經改的面目全非, 這時如果執(zhí)行 git reset, 就很難分的清哪些內容屬于被撤銷的提交了. 嗯, 這位同學說這種情況可以用 git stash 來處理, 是可以解決問題的.
但是, 身為文藝青年, 怎么能用這么不優(yōu)(zhuang)雅(bi)的方法呢.
先上結論:
如果只 amend 了一次, 那么直接用 git reset HEAD@{1} 就可以撤銷這次 amend. 如果 amend 多次, 就參考 git reflog 進行撤銷.
下面以實例介紹如何就地撤銷 git commit --amend.
制造事故現(xiàn)場
首先制造事故現(xiàn)場. 追加空行到項目中的 index.html 文件下:
$ echo "" >> index.html
$ git add .
$ git commit -m "add blank line to index.html"
然后再加一行到 index.html, 并 amend 一下:
$ echo "this line would break the code" >> index.html
$ git add .
$ git commit --amend
現(xiàn)場已經出現(xiàn), 我們要撤銷 amend 的那個提交.
撤銷 amend
首先使用 git reflog 命令查看操作記錄:
$ 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}.
現(xiàn)在可以用 git reset 將當前分支的 HEAD 指向 HEAD@{1}, 即可達到撤銷 amend 的目的:
$ 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 查看狀態(tài), 發(fā)現(xiàn) amend 的內容已經被撤銷 (到工作區(qū)) 了.
如果想撤銷到暫存區(qū), 就用 git reset --soft HEAD@{1} .
如果想干掉這個修改, 就用 git reset --hard HEAD@{1} .
這和 git reset 操作 commit 的情形是一樣的.
如果一個 commit 被 amend 了多次, 也可以用這種方法撤銷到任意一次 amend 處:
$ 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