使用 Git 管理远程仓库

记录下如何使用Git管理远程仓库,内容包括添加远程仓库,更改远程仓库的 URL,重命名远程仓库和删除远程仓库。

添加远程仓库

要新增远程,需要在存储仓库的目录中使用 git remote add 命令。

git remote add 命令使用两个参数:

示例:

1
2
3
4
5
6
7
8
# 新增一个远程仓库
git remote add origin https://github.com/user/repo.git

# 确定远程仓库信息
git remote -v

> origin https://github.com/user/repo.git (fetch)
> origin https://github.com/user/repo.git (push)

更改远程仓库的 URL

更改现有远程仓库的 URL 的命令是 git remote set-url

git remote set-url 命令使用两个参数:

  • 现有远程仓库的名称。 例如,源仓库或上游仓库是两种常见选择。
  • 远程仓库的新 URL。 例如:
    • 如果您要更新为使用 HTTPS,您的 URL 可能如下所示:
      1
      https://github.com/USERNAME/REPOSITORY.git
    • 如果您要更新为使用 SSH,您的 URL 可能如下所示:
      1
      [email protected]:USERNAME/REPOSITORY.git

将远程 URL 从 SSH 切换到 HTTPS

列出现有远程仓库以获取要更改的远程仓库的名称。

1
2
3
git remote -v
> origin [email protected]:USERNAME/REPOSITORY.git (fetch)
> origin [email protected]:USERNAME/REPOSITORY.git (push)

使用 git remote set-url 命令将远程的 URL 从 SSH 更改为 HTTPS。

1
git remote set-url origin https://github.com/USERNAME/REPOSITORY.git

验证远程 URL 是否已更改。

1
2
3
git remote -v
> origin https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin https://github.com/USERNAME/REPOSITORY.git (push)

将远程 URL 从 HTTPS 切换到 SSH

列出现有远程仓库以获取要更改的远程仓库的名称。

1
2
3
git remote -v
> origin https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin https://github.com/USERNAME/REPOSITORY.git (push)

使用 git remote set-url 命令将远程的 URL 从 HTTPS 更改为 SSH。

1
git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

验证远程 URL 是否已更改。

1
2
3
git remote -v
> origin [email protected]:USERNAME/REPOSITORY.git (fetch)
> origin [email protected]:USERNAME/REPOSITORY.git (push)

重命名远程仓库

使用 git remote rename 命令可重命名现有的远程。

git remote rename 命令使用两个参数:

  • 现有的远程名称,例如 origin
  • 远程的新名称,例如 destination

示例
以下示例假设您使用 HTTPS 克隆,即推荐使用的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 查看现有远程
git remote -v

> origin https://github.com/OWNER/REPOSITORY.git (fetch)
> origin https://github.com/OWNER/REPOSITORY.git (push)
# 将远程名称从 'origin' 更改为 'destination'
git remote rename origin destination

# 验证远程的新名称
git remote -v

> destination https://github.com/OWNER/REPOSITORY.git (fetch)
> destination https://github.com/OWNER/REPOSITORY.git (push)

删除远程仓库

使用 git remote rm 命令可从仓库中删除远程 URL。

git remote rm 命令使用一个参数:

  • 远程名称,例如 destination

示例
以下示例假设您使用 HTTPS 克隆,即推荐使用的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 查看当前远程
git remote -v

> origin https://github.com/OWNER/REPOSITORY.git (fetch)
> origin https://github.com/OWNER/REPOSITORY.git (push)
> destination https://github.com/FORKER/REPOSITORY.git (fetch)
> destination https://github.com/FORKER/REPOSITORY.git (push)
>
# 删除远程
git remote rm destination

# 验证其已删除
git remote -v

> origin https://github.com/OWNER/REPOSITORY.git (fetch)
> origin https://github.com/OWNER/REPOSITORY.git (push)