LoginSignup
2
1

More than 1 year has passed since last update.

複数gitアカウントをサクッと管理する手順メモ

Posted at

概要

複数gitアカウントをプロジェクト別に分けて使いたい時、gitの設定方法を毎回忘れているので、備忘録として残しておきます

① gitアカウント用の鍵を生成する

ssh-keygen -t rsa

どんなファイル名で保存されるか・ssh接続時に必要なパスフレーズを求められる。

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/(username)/.ssh/id_rsa):id_sub_rsa 
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

2つアカウントを管理する場合はこの手順を2回行う。
その際ファイル名は別々のものにする。

今回はid_rsasub_rsaという名前で生成。
生成した鍵は~/.sshに保存される。
ls ~/.ssh

config		id_rsa.pub	sub_rsa.pub
id_rsa		known_hosts	sub_rsa

② githubのアカウントに公開鍵を登録する

複数gitアカウントを運用する場合、それぞれのアカウントの設定 > SSH and GPG keysから公開鍵(.pub)を登録する

スクリーンショット 2022-11-30 10.45.04.png

③ ~/.ssh/configを編集

.ssh/config
#メイン
Host github-main 
  HostName github.com
  IdentityFile ~/.ssh/id_rsa
  Port 22

#サブ
Host github-sub 
  HostName github.com
  IdentityFile ~/.ssh/sub_rsa
  User git
  Port 22

④ SSH接続する

ssh -T github-main

ssh -T github-sub

Hi xxxx! You've successfully authenticated, but GitHub does not provide shell access.

メインアカウントをデフォルトで利用するように設定

git config --global user.name ${メインアカウントのユーザー名}

git config --global user.email ${メインアカウントのメールアドレス}

vim ~/.gitconfig

[user]
    name = ${メインアカウントのユーザー名}
    email = ${メインアカウントのメールアドレス}

⑤ 任意のプロジェクトにサブアカウントを紐づける

gitのグローバル設定ではメインアカウントが登録されているため、新規でプロジェクトを作成し,git管理を行うと、メインアカウントが利用される。

サブアカウントを利用する場合は別途設定が必要

テストプロジェクトを作成
mkdir git-test
cd git-test
git init

git config --local user.name ${サブアカウントのユーザー名}
git config --local user.email ${サブのメールアドレス}

vim .git/config

[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
[user]
        email = ${サブのメールアドレス}
        name = ${サブアカウントのユーザー名}

リモートリポジトリに紐づける場合

git remote add origin git@github-sub:${サブアカウントのユーザー名}/${リモートリポジトリ名}.git

git@github-subとホスト名を~/.ssh/configで設定したサブのホスト名を指定してあげるのがポイント。
(github上でリポジトリを新規作成した時の設定コマンドをそのままコピペするとこける)

参考

2
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
2
1