網頁

2021/10/7

Git revert commits 回復先前的提交

Git可使用git revert指令回復之前的提交。


git revert是新增一筆提交來反轉指定的提交異動。也就是說若原來的提交是加上一行文字,則git revert是新增一筆提交把該行文字刪除。

例如目前有以下四筆提交(commits)。

$ git log --oneline
ccf21f1 (HEAD -> master) howdy
6d06c24 hey
a351fa9 hi
168c462 add hello.txt

若要回復提交前的狀態,可輸入git revert <commit>回復指定的提交。<commit>為提交編號(commit id)。

例如回復提交 ccf21f1則可輸入git revert ccf21f1。

$ git revert ccf21f1

輸入後會開啟Vim編輯器可編輯提交紀錄訊息,若不編輯輸入:q離開

Revert "howdy"

This reverts commit ccf21f1ef9d742d4ae3af14124853568bda4df0c.

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch master
# Changes to be committed:
#       modified:   hello.txt
#
~
:q

離開Vim編輯器就完成git revert了,檢視提交紀錄已看到多了一個commit 7fc822c,提交紀錄即為Vim編輯器的內容。此新的提交即為用來回復commit ccf21f1提交的異動。

$ git log --oneline
7fc822c (HEAD -> master) Revert "howdy"
ccf21f1 howdy
6d06c24 hey
a351fa9 hi
168c462 add hello.txt

同樣地再一次用git revert 6d06c24回復commit 6d06c24提交前的狀態。

$ git revert 6d06c24
[master ea5ec0d] Revert "hey"
 1 file changed, 1 insertion(+), 2 deletions(-)

檢視提交紀錄可看到又新增了一個commit ea5ec0d用來回復commit 6d06c24

$ git log --oneline
ea5ec0d (HEAD -> master) Revert "hey"
7fc822c Revert "howdy"
ccf21f1 howdy
6d06c24 hey
a351fa9 hi
168c462 add hello.txt

若要回復上一次(最後一次)的提交可用git revert HEAD

$ git revert HEAD
[master f43ceb7] Revert "Revert "hey""
 1 file changed, 2 insertions(+), 1 deletion(-)

檢視提交紀錄新增了一個commit f43ceb7用來回復commit ea5ec0d

$ git log --oneline
f43ceb7 (HEAD -> master) Revert "Revert "hey""
ea5ec0d Revert "hey"
7fc822c Revert "howdy"
ccf21f1 howdy
6d06c24 hey
a351fa9 hi
168c462 add hello.txt

若要同時回復前3次commit,輸入git revert HEAD~3..,相當於git revert HEAD~3..HEAD

$ git revert HEAD~3..
[master 43a40e8] Revert last 3 commits
 1 file changed, 1 insertion(+), 2 deletions(-)
On branch master
Revert currently in progress.

檢視提交紀錄新增了一個commit 43a40e8用來回復三筆提交f43ceb7ea5ec0d7fc822c的異動。

$ git log --oneline
43a40e8 (HEAD -> master) Revert last 3 commits
f43ceb7 Revert "Revert "hey""
ea5ec0d Revert "hey"
7fc822c Revert "howdy"
ccf21f1 howdy
6d06c24 hey
a351fa9 hi
168c462 add hello.txt

沒有留言:

張貼留言