0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MacでGitの複数アカウント(個人用・業務用)を管理する方法

Last updated at Posted at 2025-01-02

Gitを使うとき、個人用アカウントと業務用アカウントを使い分ける必要があることはよくあります。特に、Mac上でこれを実現するには、適切な設定が必要です。本記事では、個人用と業務用フォルダを分け、それぞれのGit設定とSSH認証を適用する手順を詳しく解説します。


1. .gitconfig の設定

~/.gitconfig ファイルにフォルダごとの設定を適用します。以下のように記述してください。

[user]  # グローバル設定
    email = user@email.com
    name = username

[includeIf "gitdir:~/Documents/personal/"]  # 個人用フォルダ設定
    path = ~/.gitconfig-personal

[includeIf "gitdir:~/Documents/company/"]  # 業務用フォルダ設定
    path = ~/.gitconfig-company

上記の設定は次を意味します:

  • ~/Documents/personal/ 以下のフォルダでは ~/.gitconfig-personal の設定を使用。
  • ~/Documents/company/ 以下のフォルダでは ~/.gitconfig-company の設定を使用。

2. フォルダ別のアカウント情報設定

それぞれのフォルダで使用するGit設定ファイルを作成します。

個人用

$ vi ~/.gitconfig-personal

[user]
    name = MyGitHubName
    email = MyGitHubEmail

業務用

$ vi ~/.gitconfig-company

[user]
    name = MyCompanyGitHubName
    email = MyCompanyGitHubEmail

これで、個人用フォルダと業務用フォルダで異なる名前とメールアドレスが適用されます。

確認コマンド

$ git config user.name

⚠️ git init 済みのフォルダでのみ設定が適用されます。それ以外の場合は、グローバル設定が優先されます。

3. SSH認証の設定

SSHキーの生成

個人用と業務用でそれぞれSSHキーを生成します。


個人用キー生成

$ ssh-keygen -t ed25519 -C "MyPersonalEmail@naver.com" -f "~/.ssh/id_ed25519-personal"

業務用キー生成

$ ssh-keygen -t ed25519 -C "MyCompanyEmail@naver.com" -f "~/.ssh/id_ed25519-company"


コマンド実行後、以下のようなファイルが生成されます:

  • ~/.ssh/id_ed25519-personal と ~/.ssh/id_ed25519-personal.pub
  • ~/.ssh/id_ed25519-company と ~/.ssh/id_ed25519-company.pub

SSH設定ファイルの編集

~/.ssh/config ファイルに以下を追加します。

Host github-personal.com
    HostName github.com
    User git
    AddKeysToAgent yes
    UseKeychain yes
    IdentityFile ~/.ssh/id_ed25519-personal

Host github-company.com
    HostName github.com
    User git
    AddKeysToAgent yes
    UseKeychain yes
    IdentityFile ~/.ssh/id_ed25519-company

4. 動作確認

クローンテスト

それぞれのアカウントでGitリポジトリをクローンします。


個人用リポジトリのクローン

$ git clone git@github-personal.com:[username]/[repository-name].git

業務用リポジトリのクローン

$ git clone git@github-company.com:[username]/[repository-name].git

⚠️ Permission denied (publickey) エラーが出た場合、以下の方法で解決してください。

SSHキーの登録

GitHubにSSHキーを登録します。

  1. 個人用キーを表示:

    $ cat ~/.ssh/id_ed25519-personal.pub
  2. 表示されたキーをコピーして、GitHubSettingsSSH and GPG keysNew SSH Key に追加します。
  3. 同様に業務用キーも登録します。

5. まとめ

これで、1台のMacで個人用と業務用のアカウントをスムーズに管理できるようになりました。~/.gitconfig の設定により、各フォルダで適切なユーザー情報が自動的に適用されます。また、SSH認証を完了することで、アカウントの衝突を避けつつ快適に作業ができます。

参考になりましたか?フィードバックや質問があればコメントで教えてください! 😊

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?