你無法修改 Git 的記錄

來源:互聯網
上載者:User

標籤:http   使用   os   資料   問題   re   

轉自:http://www.oschina.net/news/26241/you-can-not-change-git-history

有時候使用Git工作得小心翼翼,特別是涉及到一些進階操作,例如 reset, rebase 和 merge。甚至一些很小的操作,例如刪除一個分支,我都擔心資料丟失。

不久之前,我在做一些大動作(rebasing)之前,我總是備份整個版本庫,以防萬一。直到最近我才發現git的記錄是不可修改的,也就是說你不能更改任何已經發生的事情。你做的任何操作都只是在原來的操作上修改。也就是說,即使你刪除了一個分支,修改了一個提交,或者強制重設,你仍然可以復原這些操作。

讓我們來看一些例子:

$ git init
$ touch foo.txt
$ git add foo.txt
$ git commit -m "initial commit"

$ echo ‘new data‘ >> foo.txt
$ git commit -a -m "more stuff added to foo"

你現在看git的記錄,你可以看到兩次提交:
$ git log
* 98abc5a (HEAD, master) more stuff added to foo
* b7057a9 initial commit

現在讓我們來重設回第一次提交的狀態:
$ git reset --hard b7057a9
$ git log
* b7057a9 (HEAD, master) initial commit

這看起來我們是丟掉了我們第二次的提交,沒有辦法找回來了。但是 reflog 就是用來解決這個問題的。簡單的說,它會記錄所有HEAD的曆史,也就是說當你做 reset,checkout等操作的時候,這些操作會被記錄在reflog中。

$ git reflog
b7057a9 [email protected]{0}: reset: moving to b7057a9
98abc5a [email protected]{1}: commit: more stuff added to foo
b7057a9 [email protected]{2}: commit (initial): initial commit

所以,我們要找回我們第二commit,只需要做如下操作:
$ git reset --hard 98abc5a

再來看一下 git 記錄:
$ git log
* 98abc5a (HEAD, master) more stuff added to foo
* b7057a9 initial commit

所以,如果你因為reset等操作丟失一個提交的時候,你總是可以把它找回來。除非你的操作已經被git當做垃圾處理掉了,一般是30天以後。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.