git rebase

Rebase branch and repositories

Posted by Eirik on 2 Mar, 2024

In your local clone of your forked repository, you can add the original GitHub repository as a “remote”. (“Remotes” are like nicknames for the URLs of repositories - origin is one, for example.) Then you can fetch all the branches from that upstream repository, and rebase your work to continue working on the upstream version.

到你 fork repository 的 local cloned area 中,你可以將原始 GitHub 存儲庫添加為remote(就像是 repository URL 的別名 - origin 就是其一)然後,你可以從上游 repository 中取回所有分支,並重新定位你的工作以繼續在上游版本上進行工作。

Add the remote, call it “upstream”: In terms of commands that might look like:

命令可能如以下操作:添加remote,將其命名為 upstream

git remote add upstream <remote git URL>

Fetch all the branches of that remote into remote-tracking branches, such as upstream/master:

將該遠端的所有分支提取到遠端跟踪分支中,例如 upstream/master:

git fetch upstream

Make sure that you’re on your master branch:

確保你在你的 master 分支上:

git checkout master

Rewrite your master branch so that any commits of yours that aren’t already in upstream/master are replayed on top of that other branch:

重寫你的 master 分支,使你的任何commit(如果尚未存在於 upstream/master)都在該分支的頂部重放:

git rebase upstream/master

If you don’t want to rewrite the history of your master branch, (for example because other people may have cloned it) then you should replace the last command with git merge upstream/master. However, for making further pull requests that are as clean as possible, it’s probably better to rebase.

如果你不想重寫你的 master 分支的歷史(例如因為其他人可能已 clone了它),那麼你應該用 git merge upstream/master 來替換最後一個命令。但是,為了製作盡可能乾淨的進一步fetch請求,最好還是使用 rebase。

If you’ve rebased your branch onto upstream/master you may need to force the push in order to push it to your own forked repository on GitHub. You’d do that with:

如果你已經將你的分支重寫到 upstream/master 上,你可能需要強制 push 以將其 push 到 GitHub 上的你自己的 forked repository 中。你可以使用以下命令來實現:

git push -f origin master

You only need to use the -f the first time after you’ve rebased.

在重寫後的第一次推送時才需要使用 -f。