Pushing to multiple github accounts from the same machine
Sometimes one has to use several github accounts from the same machine (maybe one has a specific account for work, in addition of one's default hobby account), and when tryig to push from a local repo, there could be problems as git may not see the alternative account.
There are two areas that need configured deliberately for this setup to work: git config and SSH config.
Git config
Normally, git configuration is defined by default in ~/.gitconfig
That's where configuration directive sets with --global go.
That' also wher the email I use for my default github account is set:
to add support for an alternate account, you need to choose another location for an alternate configuration file and the following block in the default config file:
Here I chose ~/dev/alternate/ to have the alternate configuration. Then create ~/dev/alternate/.gitconfig:
To figure whether the above setup works and which config git is using, you can run from a repository inside the alternate location and from outside:
The value shown will be the alternate email and the main one respectively.
Note
Any git repository that pertains to the alternate account must be inside the directory you have used in the includeIf directive.
SSH config
You need to have two sets of SSH keys for each github account.
Then you need to have the public key (*.pub) to be added in github.com's SSH Keys settings for each user.
Then ensure the default user SSH configuration at ~/.ssh/config has the three blocks below:
IdentitiesOnly yes
Host gh-main
AddKeysToAgent yes
UseKeychain yes
HostName github.com
User git
IdentityFile /Users/username/.ssh/main_github
Host gh-alt
AddKeysToAgent yes
UseKeychain yes
HostName github.com
User git
IdentityFile /Users/username/.ssh/alt_github
Example
To add a remote for the main account use git remote add origin git@gh-main:mainaccount/my-repo.git (or git remote set-url origin git@gh-main:mainaccount/my-repo.git when updating existing remote).
To add a remote for the alternate account use git remote add origin git@gh-alt:altaccount/my-repo-alt.git (or git remote set-url origin git@gh-alt:altaccount/my-repo-alt.git when updating existing remote).
Same with cloning: git clone git@gh-main:mainaccount/some-repo.git or git clone git@gh-alt:altaccount/another-repo.git
Troubleshoooting
To test the ssh connection, you can use:
If they are issues, you can test the specific SSH Key created for a given github account
where the -F /dev/null parameter tells SSH to not read the configuration file and -vvv active 3 levels of debug information.
Warning
That's the command that helped me figure that without the IdentitiesOnly=yes directive, ssh will try all the SSH keys in ~/.ssh/ even if IdentityFile or -i is specified, so that if you happen to have a SSH key used in another github account, it may connect to the wrong one.