LoginSignup
2
0

More than 1 year has passed since last update.

git configのincludeIfを使ってgithubアカウントを複数使い分ける

Last updated at Posted at 2021-07-30

githubでメインアカウント、サブアカウントがあるとして
アカウントを使い分けられるように設定していきます。

githubのssh接続先を分ける

.ssh/configの接続先を分けます。

Host github # メインのgithubアカウント用
  HostName github.com
  User company-user
  IdentityFile ~/.ssh/id_rsa_github_company
  IdentitiesOnly yes
Host github-sub # サブ用。github.com以外の任意のHost名
  HostName github.com
  User private-user
  IdentityFile ~/.ssh/id_rsa_github_private
  IdentitiesOnly yes

上記の接続先の設定で接続テストができるか確認。

$ ssh -T git@github-sub
Hi {githubのID}! You've successfully authenticated, but GitHub does not provide shell access

これでサブのアカウントでgit cloneできるようになりました。

$ git clone git@github-sub:{githubのID}/{リポジトリ名}.git

作業ディレクトリ単位でアカウントを切り替える

git clone、git pushはssh接続先を複数設定することで出来るようになりましたが、
これだとuser.nameとuser.emailの設定が足りないので、コミットにそれぞれのuser.name、user.emailが追加されません。
メインアカウントとサブアカウントとでuser.nameとuser.emailの設定も切り替えられるようにしたいところ。

ただ、git config --globalだと共通の設定になってしまうし、
git config --localだと対象リポジトリ内のみで都度設定するのは手間なので
メインとサブの作業ディレクトリを分けて、それぞれの作業ディレクトリ下でgit cloneしたリポジトリには
ユーザー情報がメインとサブでそれぞれ設定されるようにしたい。

作業ディレクトリはこういうイメージ。

/user/to/path/
├ workspace-main/ # メインアカウントのリポジトリはこっちにgit cloneしたい 
└ workspace-sub/ # サブアカウントのリポジトリはこっち

.gitconfigでディレクトリ毎の設定を分ける

下記のような.gitconfigファイルを設置します。

~/
├ .gitconfig
├ .gitconfig-main # メイン用設定ファイル
└ .gitconfig-sub # サブ用設定ファイル

仕事用githubユーザー情報を.gitconfig-mainに、
同様にプライベートのgithubユーザー情報を.gitconfig-subにそれぞれ設定。

.gitconfig-main

[user]
  name  = main-user
  email = main-user@example.com

.gitconfig-sub

[user]
  name  = sub-user
  email = sub-user@example.com

.gitconfigに includeIf で作業ディレクトリ毎に読み込むファイルを追記。

[user]
  [includeIf "gitdir:/user/to/path/workspace-main/"]
    path = ~/.gitconfig_main

  [includeIf "gitdir:/user/to/path/workspace-sub/"]
    path = ~/.gitconfig_sub

各作業ディレクトリ下でgit cloneしたリポジトリで設定したユーザー情報が確認できたら完了です。

$ cd /user/to/path/workspace-sub/nanika-no-repository/
$ git config --list
user.name=sub-user
user.email=sub-user@example.com
2
0
1

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
0