git commit --amend的撤銷方法


某同事執行git commit 時太興奮,執行了

git commit --amend

慌了,不敢編輯上一個commit的description了,直接選擇了wq退出,然而git畢竟強大,默認將改動合並提交並覆蓋了上一個commit生成了一個新的commit id,這下更慌了,上一個commit idgit log里沒了,沒了,沒了
此時只有兩個字,奔潰

好在git有撤銷方法,下面的代碼拿來舉例。


當前代碼倉有如下文件:

$ ll
total 4
-rw-r--r-- 1 ****** 1051817 3 九月 13 15:49 1.txt
-rw-r--r-- 1 ****** 1051817 3 九月 13 16:00 2.txt
-rw-r--r-- 1 ****** 1051817 2 九月 13 14:16 3.txt
-rw-r--r-- 1 ****** 1051817 7 九月 13 13:54 README.md

修改1.txt2.txt,並提交。

$ echo "12" >> 1.txt
$ echo "22" >> 2.txt
$ git add .
$ git commit -m "modified 1/2.txt"
[master b82585f] modified 1/2.txt
 3 files changed, 3 insertions(+)
 create mode 100644 3.txt

在未push前,繼續修改3.txt,並執行git commit --amend覆蓋上一個commit。

$ echo "32" >> 3.txt
$ git add 3.txt
$ git commit --amend
[master 6889e84] modified 1/2/3.txt
 Date: Thu Sep 14 14:18:40 2017 +0800
 3 files changed, 4 insertions(+)
 create mode 100644 3.txt

執行git log發現最新的commit id 已經從b82585f變為了6889e84

$ git log
commit 6889e8402d8f40b38f5e6c0aff686b6b3ca82389 (HEAD -> master)
Author: ******
Date:   Thu Sep 14 14:18:40 2017 +0800

    modified 1/2/3.txt

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
nothing to commit, working tree clean,

這就演示到文章開頭同事遇到的問題了,amend覆蓋了上一個commit,且提交了對文件的修改,只是他未修改description。


撤銷開始

如果我們忘記了被覆蓋的那個commit id,那就用reflog命令看一下

$ git reflog
6889e84 (HEAD -> master) HEAD@{0}: commit (amend): modified 1/2/3.txt
b82585f HEAD@{1}: commit: modified 1/2.txt

$ git reset b82585f
Unstaged changes after reset:
M       3.txt

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (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:   3.txt

no changes added to commit (use "git add" and/or "git commit -a")

$ git log
commit b82585f65b4c467a7e5855191b73a613fcf20892 (HEAD -> master)
Author: ares.wang <ares.wang@seraphic-corp.com>
Date:   Thu Sep 14 14:18:40 2017 +0800

    modified 1/2.txt 

可以看出,reset已經恢復到上一個被覆蓋的commit id了,且對文件的修改回退到代碼倉not staged的狀態了

不使用 git reset --hard的目的就是為了保留本地修改,否則修改就會被丟棄!演示如下:

$ git reset --hard b82585f
HEAD is now at b82585f modified 1/2.txt

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
nothing to commit, working tree clean

3.txt的modified沒有了,切記慎用--hard參數,除非你確定放棄當前未提交的所有修改!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM