簡體   English   中英

如何在不刪除最新提交的情況下恢復到上一個提交?

[英]How do I revert to the previous commit without deleting the latest commit?

假設我有 2 個提交已經推送到我的遠程分支。

  • 提交 A(2021 年 5 月 31 日)
  • 提交 B(2021 年 5 月 30 日)

如何在不刪除提交 A 的情況下恢復到提交 B? 我只想比較這兩個提交之間的結果。

注意:不需要代碼比較。 我只想比較 Commit A 與 Commit B 的 output

我強烈不同意其他建議您使用git revert的答案。 這實際上會恢復提交 A引入的更改並自行生成提交。

由於您想在某個時間點查看 state,您可以直接簽出Commit B ,以便檢查內容。 然后將原始分支檢出到 go 回到最新的提交。

git checkout $HASH_OF_COMMIT_B   # now you are in a detached head state at commit B
git checkout $BRANCH             # now you are back at the tip of the branch (commit A)

很多工具可以讓你直接看到兩個引用之間的區別,而無需檢查。 在命令行上,這可以通過git diff來完成:

git diff $HASH_OF_COMMIT_A..$HASH_OF_COMMIT_B

如何在不刪除提交 A 的情況下恢復到提交 B?

您可以輕松使用git rebase -i <commit_hash>

  • Select 在提交 B 之前提交一次,即提交 C

HEAD <- 提交 A <- 提交 B <- 提交 C

  • git rebase -i <commit_hash_commitC>
  • 上面的命令將在您的文本編輯器中列出提交,如下所示:
 pick f7f3f6d Commit B pick a5f4a0d Commit A # Rebase 710f0f8..a5f4a0d onto 710f0f8 # # Commands: # p, pick <commit> = use commit # r, reword <commit> = use commit, but edit the commit message # e, edit <commit> = use commit, but stop for amending # s, squash <commit> = use commit, but meld into previous commit # f, fixup <commit> = like "squash", but discard this commit's log message # x, exec <command> = run command (the rest of the line) using shell # b, break = stop here (continue rebase later with 'git rebase --continue') # d, drop <commit> = remove commit # l, label <label> = label current HEAD with a name # t, reset <label> = reset HEAD to a label # m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] #. create a merge commit using the original merge commit's #. message (or the oneline, if no original merge commit was #. specified). Use -c <commit> to reword the commit message. # # These lines can be re-ordered; they are executed from top to bottom. # # If you remove a line here THAT COMMIT WILL BE LOST. # # However, if you remove everything, the rebase will be aborted. # # Note that empty commits are commented out
  • 刪除代表提交 B 的行,然后保存並退出文本編輯器。
  • Git 將重播交互式編輯器中提到的所有提交並將停止,這將完全刪除提交 B。

您可以進行交互式變基,刪除您不需要的提交,並在您的刪除分支上進行硬推送。

git rebase -i     //opens interactive rebasing window

pick #commitID2 My commit 2
pick #commitID1 My commit 1    <- To unpick/remove this commit, using editor remove 
                                  line->

save the window.
git push origin branchname -f 

恢復提交 B不會刪除提交A。它只會創建提交 C ,這將撤消您在提交 B中所做的一切

git revert commit-b-hash
git revert <Commit B>

給定一個或多個現有提交,還原相關補丁引入的更改,並記錄一些記錄它們的新提交。 這要求您的工作樹是干凈的(不修改 HEAD 提交)。 git 文檔


但是,如果您只想查看兩者之間的區別:

git diff <Commit B>..<Commit A>

顯示工作樹和索引或樹之間的更改、索引和樹之間的更改、兩棵樹之間的更改、合並導致的更改、兩個 blob 對象之間的更改或磁盤上兩個文件之間的更改。 git 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM