LoginSignup
1
1

More than 3 years have passed since last update.

Gitで複数アカウントを使い分ける時のリモート接続設定メモ

Last updated at Posted at 2020-08-01

[備忘] 複数Githubアカウントでssh接続設定(config)を使い分ける手順
git pushする前にアカウント切り替えたい時どうやるんだっけ…?となり、こちらの方の記事を自分用にアレンジした時のメモです。
上記の方が丁寧なので、基本は上記を読んだ方がよいと思います。

事前準備

以下は準備済みの前提で進めます。この記事では説明を省略しています。

  • gitリポジトリ
  • GitHubなどのアカウント (必要な数だけ)
  • ssh鍵の生成およびGitHub等への登録 (必要な数だけ)
  • globalのgit設定全般

ssh設定

今回は、メインのアカウントは(コマンドコピペ時などにそのまま使えるように)通常通り Host: github.com とし、サブのアカウントを使うときは Host 末尾に .sub と加えることで使い分けるようにします。

~/.ssh/config
Host github.com
  User git
  IdentityFile ~/.ssh/id_rsa_main
  TCPKeepAlive yes
  IdentitiesOnly yes

Host github.com.sub
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_sub
  TCPKeepAlive yes
  IdentitiesOnly yes

接続確認

$ ssh -T git@github.com
$ ssh -T git@github.com.sub

設定がうまくできていれば、それぞれのレスポンスでアカウント名部分が変わるはずです。

Hi {your-account}! You've successfully authenticated, but GitHub does not provide shell access.

git設定 (subのアカウントの例のみ)

リポジトリ内のアカウント設定

サブのアカウントに切り替えたいリポジトリ配下で以下を実行。最初のcommitをする前にやっておきたい。

git config --local user.name {sub-account}
git config --local user.email {sub-email}

リモートリポジトリURLの登録

$ git remote add origin git@github.com.sub:{your-sub-account}/{repository-name}.git

既に remote.origin.url に何かしらが入っていると fatal: remote origin already exists. と怒られてできないので、その場合は以下コマンドのように add ではなく set-url とする。

$ git remote set-url origin git@github.com.sub:{your-sub-account}/{repository-name}.git

確認

$ git config remote.origin.url
git@github.com.sub:{your-sub-account}/{repository-name}.git

ホスト名部分が github.com.sub など、.ssh/config の Host 部分に書いた値と同じにできていればOK。

これで複数アカウントでのcloneやpushが快適にできるようになりました!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1