Victor's Code Journey
Victor's Code Journey

目录

git多账号通过ssh提交

注意
本文最后更新于 2025-10-29,文中内容可能已过时。

假设我有两个 github 账号,victor(for personal) 和 superman(for work)。如果我想在同一台电脑上使用这两个账号进行 git push/pull。该如何配置?

  1. 由于github 现在已经不支持 http 方式 push。所以首先需要生成 ssh key,并将 ssh key 加入 github 账号.

  2. 按照如下方式设置 ssh 配置文件~/.ssh/config

## work github account: superman
Host github.superman
   HostName github.com
   User git
   IdentityFile ~/.ssh/superman_private_key
   IdentitiesOnly yes
   
## personal github account: victor
Host github.com
   HostName github.com
   User git
   IdentityFile ~/.ssh/victor_private_key
   IdentitiesOnly yes
  1. 向 ssh agent 中加入私钥
$ ssh-add ~/.ssh/victor_private_key
$ ssh-add ~/.ssh/superman_private_key
  1. 测试连接
$ ssh -T git@github.com
$ ssh -T git@github.superman
  1. 克隆项目
## 工作项目克隆
$ git clone git@github.superman:xxx/project1.git /path/to/project1
$ cd /path/to/project1
$ git config user.email "superman@example.com"
$ git config user.name  "Super Man"
## 个人项目克隆
$ git clone git@github.com:xxx/project2.git /path/to/project2
$ cd /path/to/project2
$ git config user.email "Victor@example.com"
$ git config user.name  "Victor"

通过指定私钥文件来临时支持。

GIT_SSH_COMMAND='ssh -i PATH/TO/KEY/FILE -o IdentitiesOnly=yes' git clone git@github.com:OWNER/REPOSITORY

上面的命令也可以封装为脚本git-me.sh:

#!/usr/bin/env bash

SSH_PRIVATE_KEY=~/.ssh/personal_private_key.pem

GIT_SSH_COMMAND="ssh -i $SSH_PRIVATE_KEY -o IdentitiesOnly=yes" git $@

相关内容