Git 远程仓库是一个指向仓库另一副本的引用,通常托管在远程服务器上。当你 git clone 一个仓库时,Git 会自动创建一个名为 origin 的远程仓库,指向克隆的 URL。

在项目协作中,你可能会使用多个远程仓库。如果某个远程仓库迁移到了其他主机,或者某个贡献者不再提交贡献,你可能希望从本地仓库中移除该远程仓库。

本指南介绍如何使用 git remote rm 命令移除 Git 远程仓库。

如果你需要先创建一个新的远程仓库,请参阅我们的添加 Git 远程仓库指南。如果你需要更新 URL,请参阅我们的更改 Git 远程仓库 URL 指南。

列出远程仓库

在移除远程仓库之前,使用 git remote -v 列出当前的远程连接:

终端
git remote -v
输出
origin	https://github.com/user/repo.git (fetch)
origin	https://github.com/user/repo.git (push)
testing	git@gitserver.com:user/repo.git (fetch)
testing	git@gitserver.com:user/repo.git (push)

移除远程仓库

要移除远程仓库,使用 git remote rm 命令后跟远程仓库名称:

终端
git remote rm <remote-name>

例如,移除名为 testing 的远程仓库:

终端
git remote rm testing

你也可以使用长格式 git remote remove,效果相同:

终端
git remote remove testing

该命令会从本地配置中移除对该远程仓库的所有引用。它不会删除远程服务器上的仓库。

要验证远程仓库是否已成功移除,再次运行 git remote -v:

终端
git remote -v
输出
origin	https://github.com/user/repo.git (fetch)
origin	https://github.com/user/repo.git (push)

testing 远程仓库不再列出。

移除了哪些内容 #

当你运行 git remote rm 时,Git 会移除:

  • 来自 .git/config 文件的远程仓库条目
  • 与该远程仓库关联的所有远程跟踪分支(例如 testing/main、testing/dev)

这就是为什么使用 git remote rm 比手动编辑 .git/config 更受推荐——该命令会自动清理跟踪引用。

错误:没有该远程仓库 #

如果你尝试移除的远程仓库不存在,Git 会打印错误信息:

输出
fatal: No such remote: 'testing'

使用 git remote -v 验证远程仓库名称,然后重试。

重命名远程仓库

如果你需要更改远程仓库的名称而不是移除它,使用 git remote rename 命令:

终端
git remote rename <old-name> <new-name>

例如,将 testing 重命名为 staging:

终端
git remote rename testing staging

这会更新所有远程跟踪分支以使用新名称。

故障排除

运行 git remote rm 时出现 fatal: No such remote
运行 git remote -v 验证确切的远程仓库名称。远程仓库名称区分大小写。

移除远程仓库后,本地分支的上游显示 gone
你的本地分支仍然存在,但其上游引用随远程仓库一起被移除了。使用 git branch --set-upstream-to=<remote>/<branch> <local-branch> 设置新的上游,或使用 git branch --unset-upstream <local-branch> 取消设置。

快速参考

命令描述
git remote -v列出所有远程仓库
git remote rm <name>移除一个远程仓库
git remote remove <name>移除一个远程仓库(长格式)
git remote rename <old> <new>重命名一个远程仓库

常见问题

移除远程仓库会删除服务器上的仓库吗?
不会。git remote rm 命令只移除本地引用。远程仓库保持不变。

移除远程仓库时,跟踪分支会怎样?
与该远程仓库关联的所有远程跟踪分支(例如 testing/main)会从你的本地仓库中删除。跟踪这些远程分支的本地分支不会被删除,但将不再有上游。

移除远程仓库后可以重新添加吗?
可以。随时使用 git remote add <name> <url> 重新添加远程仓库。