仕事用とプライベート用で別のGitHubアカウントを使用する際などに、うまいこと使い分ける方法をメモします。
公開鍵・秘密鍵を作成する
新しいGithubアカウントのsshキーを作成していない場合は以下のコマンドを実行して、鍵を生成
$ cd ~/.ssh
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
# id_rsa_secondという名前で作成
Enter file in which to save the key (/Users/(username)/.ssh/id_rsa): id_rsa_second
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
※ 念のためバックアップをとっておくと安心
$ cd ~/.ssh
$ cp id_rsa_second id_rsa_second_bk
$ cp id_rsa_second.pub id_rsa_second_bk.pub
configファイルにSSH設定を追加する
$ vi ~/.ssh/config
------
Host github
User git
Port 22
HostName github.com
IdentityFile ~/.ssh/id_rsa
TCPKeepAlive yes
IdentitiesOnly yes
Host github_second
User git
Port 22
HostName github.com
IdentityFile ~/.ssh/id_rsa_second
TCPKeepAlive yes
IdentitiesOnly yes
公開鍵をGitHubにアップする
1. 公開鍵をコピーする
# id_rsa_secondの公開鍵の中身を確認する場合
cat ~/.ssh/id_rsa_second.pub
2. githubアカウントにコピーした公開鍵をペースト
https://github.com/settings/ssh
ローカルリポジトリのリモート設定を管理先のアカウントに変更する
# github_secondのリモートリポジトリに接続する場合
$ git remote add origin git@github_second:"WORK_ACCOUNT"/"REPOSITORY"
# github_secondのリモートリポジトリからクローンする場合
$ git clone git@github_second:"WORK_ACCOUNT"/"REPOSITORY"
アカウント切り替え
以下でアカウントの切り替えができる
$ git config --global user.name "<YOUR_NAME>"
$ git config --global user.email <YUOR_EMAIL>
毎回コマンド打つのがめんどくさいので、シェルを作っておくと楽
function gitMain() {
git config --global user.name "<MAIN_ACCOUNT>"
git config --global user.email <MAIN_ADDRESS>
git config --list
}
function gitSecond() {
git config --global user.name "<SECOND_ACCOUNT>"
git config --global user.email <SECOND_ADDRESS>
git config --list
}
コメント