1. 添加 upstream 远程仓库
如果你是从一个仓库 fork 下来的,通常需要将原始仓库作为 upstream 远程仓库。假设原始仓库的 URL 是 https://github.com/username/repository.git,你可以通过以下命令将其添加为 upstream:
git remote add upstream <上游仓库>
2. 获取远程 upstream 信息
添加了 upstream 后,执行以下命令来获取 upstream 的所有更新:
git fetch upstream
3. 执行 Rebase
一旦获取了 upstream 的信息,你可以执行 rebase 操作:
git rebase upstream/main
确保你在一个正确的本地分支(比如 main)上,或者根据需要切换到你想要进行 rebase 的分支。
查看是否添加成功
git remote -v
答疑:
- 执行 git rebase upstream/main,出现如下error:
error: cannot rebase: You have unstaged changes.
error: Please commit or stash them.
这个报错的意思是你本地有未暂存(unstaged)的改动,Git 不允许你在有未暂存改动的情况下进行 rebase。
解决方案:把改动暂存起来(stash),等 rebase 完再还原
git stash save "临时保存改动"
git rebase upstream/main
git stash pop