とうゆのメモ帳

日常とか勉強とか

ディレクトリ毎にgitの設定を切り替える方法

会社用と個人用等でディレクトリを分けて、gitconfigを切り替えたい場合

構成例

会社用ディレクトリ構成

~/company_repos
    ├─ RepositoryA
    └─ RepositoryB

個人用ディレクトリ構成

~/private_repos
    ├─ RepositoryC
    └─ RepositoryD

設定方法

$ mkdir ~/.gitconfig_profiles

$ echo -e "
[core]
\tsshCommand = "ssh -i ~/.ssh/${company用_id_rsa}_id_rsa -F /dev/null"
[user] 
\tname = company_username
\temail = company@address.com
"  > ~/.gitconfig_profiles/company

$ echo -e "
[core]
\tsshCommand = "ssh -i ~/.ssh/${private用_id_rsa}_id_rsa -F /dev/null"
[user] 
\tname = private_username
\temail = private@address.com
"  > ~/.gitconfig_profiles/private

$ git config --global -e

[user]直下に、以下を追加

[includeIf "gitdir:~/company_repos/"]
        path = ~/.gitconfig_profiles/company
[includeIf "gitdir:~/private_repos/"]
        path = ~/.gitconfig_profiles/private

Note:

  • .gitconfig_profilesのディレクトリを作成しprofile毎に管理
  • [core] 部分にプロファイルに応じてssh keyの切り替えを設定を記述
  • echo -eは、エスケープシーケンスを使用するため