How to work with multiple git accounts on a single machine?
- Posted on
- Authors
- Name
- ansidev
- @ansidev
Problem
Assuming I have two Github accounts:
gh-user1
(email: [email protected]).gh-user2
(email: [email protected]).
I am using gh-user1 as the global GitHub account on my local computer.
Now I want to setup my computer to commit and push as gh-user2
on project X.
How can I setup the account gh-user2
on my local computer?
Solution
Steps
- Generating a new SSH key and adding it to the ssh-agent.
- Adding a new SSH key to your GitHub account.
- Generating a new GPG key.
- Adding a GPG key to your GitHub account.
- Open the terminal and cd into root folder of project X.
- Run following commands:
# Setup user email
git config --local user.email '[email protected]'.
# Setup user display name
git config --local user.name 'Your display name'
# Setup ssh command to forcing use the specific private key for this Git project only
git config --local core.sshCommand 'ssh -i /path/to/your-ssh-private-key'
# Setup local GPG signing key
git config --local user.signingkey {your_gpg_signing_key_id}
# Enable signing commit feature
git config --local commit.gpgsign true
# Setup user email
git config --local user.email '[email protected]'.
# Setup user display name
git config --local user.name 'Your display name'
# Setup ssh command to forcing use the specific private key for this Git project only
git config --local core.sshCommand 'ssh -i /path/to/your-ssh-private-key'
# Setup local GPG signing key
git config --local user.signingkey {your_gpg_signing_key_id}
# Enable signing commit feature
git config --local commit.gpgsign true
You can add an alias to your shell command for easily applying.
alias git-gh-user-2="git config --local user.email '[email protected]' && git config --local user.name 'Your display name' && git config --local user.signingkey {your_gpg_signing_key_id} && git config --local commit.gpgsign true && git config --local commit.gpgsign true"
alias git-gh-user-2="git config --local user.email '[email protected]' && git config --local user.name 'Your display name' && git config --local user.signingkey {your_gpg_signing_key_id} && git config --local commit.gpgsign true && git config --local commit.gpgsign true"
For the future project, if you want to commit and push as gh-user2 on new projects, just cd into the project and run the alias command.
Conclusion
You can find many other solutions on the Internet. If it works for you, just use them.
I am using 2 GitHub accounts for this solution but you can apply it for other Git hosting providers (GitLab, BitBucket, etc…).
If you find my articles and projects useful to you, consider donating to me at: