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?

Github複数アカウント管理方法

Posted at

はじめに

Web上でGithubのアカウントを切り替え可能になったが、それぞれのアカウントに対して1台のPCから作業を行う際に必要となる設定の忘備録として残しておく。

秘密鍵・公開鍵を生成する

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/ユーザー名/.ssh/id_rsa): <--鍵の保存先 
Enter passphrase (empty for no passphrase):  <-- パスフレーズを入力(任意)
Enter same passphrase again:  <-- もう一度、パスフレーズを入力(任意)

サブの場合はわかりやすいようにsubを名前に入れておく。
Githubへのsshキーの登録方法は割愛。

設定ファイルの変更

ssh経由でのリモートサーバーの接続する際に利用される設定ファイルの変更を行う。

~/.ssh/config
Host github-sub
  HostName github.com
  IdentityFile ~/.ssh/github_sub
  User git
  Port 22
  TCPKeepAlive yes
  IdentitiesOnly yes

zshの設定ファイルの変更

ターミナル上でGithubのアカウントを切り替えられるようにしておく

~/.zshrc
function gitmain() {
  git config --global user.name <githubのユーザー名>
  git config --global user.email <メールアドレス>
  source ~/.zshrc
}

function gitsub() {
  git config --global user.name <githubのユーザー名>
  git config --global user.email <メールアドレス>
  source ~/.zshrc
}

export PROMPT="
%F{green}[%~]%f <`git config user.name`>
=> %# "
RPROMPT='%*'

それぞれ、gitmain, gitsub コマンドの実行でアカウントを切り替える。
切り替える際に source ~/.zshrc (反映)も自動で行うようにしておく。

export PROMPT は現在のアカウントを常に表示しておくためのカスタマイズ設定で、以下のように表示される。

[~/path/hoge] <user.name>

ssh-agentに鍵追加

以下のように表示された場合追加が必要。(権限不足でgit pushできない)

$ ssh-add -l 
The agent has no identities.

毎回手動で秘密鍵を登録するのは面倒なので、起動のたびに自動で登録まで行われるようにzshの設定ファイルを変更する。

~/.zshrc
# 既存の ssh-agent プロセスをチェック
if ! pgrep -u "$USER" ssh-agent > /dev/null; then
    eval "$(ssh-agent -s)"
fi

# ssh-add の前に鍵がすでに登録されているか確認
if ! ssh-add -l | grep -q "github_sub"; then
    ssh-add ~/.ssh/github_sub
fi

これでターミナルを起動するたびに登録されていなければ自動で鍵を登録してくれる。

おわり

以上でGithub上のそれぞれのアカウントに1台のPCからGit操作を行うことができる。

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?