I have two Github accounts: user1 (personal) and user2 (for work). I want to use both accounts on same computer (without typing password everytime, when doing git push or pull).
Use ssh keys and define host aliases in ssh config file (each alias for an account). AND use diffrent .gitconfig user credentials depending on what directory you're currently working in.
Make sure your current directory is root. In root you should already have a .ssh folder by default. Since it's a dot folder you need to do ls -a
in order to see it. If you don't have any, you can create one with mkdir .ssh
.
$ ssh-keygen -t rsa -b 8192 -C "[email protected]" -f "github-user1"
$ ssh-keygen -t rsa -b 8192 -C "[email protected]" -f "github-user2"
-C flag adds a comment to help identify the key.
-f flag specifies the file name for the key pair.
For passphrase, you can add one or ignore it by pressing enter
Now you should have public and private keys for both your accounts in your ~/.ssh/
directory.
$ ssh-add --apple-use-keychain ~/.ssh/github-user1
$ ssh-add --apple-use-keychain ~/.ssh/github-user2
To see all entries added, use ssh-add -l
If you dont have one, run touch config
. Add these lines to your config file:
Host github.com-user1
HostName github.com
User git
UseKeychain yes
IdentityFile ~/.ssh/github-user1
Host github.com-user2
HostName github.com
User git
UseKeychain yes
IdentityFile ~/.ssh/github-user2
Sign in to corresponding github account and add the public ssh key in Settings -> SSH and GPL Keys. Copy the correct keys by running
$ pbcopy < ~/.ssh/github-user1.pub
$ pbcopy < ~/.ssh/github-user2.pub
ssh -T [email protected]
ssh -T [email protected]
We should get a response similar to this:
Hi user1! You've successfully authenticated, but GitHub does not provide shell access.
Repository in github will show this clone URL:
git clone [email protected]:AccountName/pathtoproject.git
Here you need to add your username like this:
git clone [email protected]:AccountName/pathtoproject.git
useful tip is to check your remotes using:
git remote -v
if you want to be sure before committing, you can check current gitconfig by running git config --list
Note that git config --list
does display both
global and local gitconfig. You local can be found in .git/config
Add this to your .gitconfig in root:
[includeIf “gitdir:~/code/privat/“]
path = ~/.gitconfig-privat
[includeIf “gitdir:~/code/work/“]
path = ~/.gitconfig-work
Now create the .gitconfig-private
and .gitconfig-work
files in root (touch .gitconfig-private
and touch .gitconfig-work
)
And add the following to respective file:
[user]
name = user1
email = [email protected]
And thats is! 🏁
Got stuck or got any feedback? Please leave a comment! ✍️
Considered this helpfull? Please star the repo 🌟