Multiple GitHub accounts on the same computer?
Asked Answered
T

42

790

Trying to work on both my actual "work" repos, and my repos on GitHub, from my computer.

The work account was set up first, and everything works flawlessly.

My account, however, cannot seem to push to my repo, which is set up under a different account/email.

I've tried copying my work key up to my account, but that throws an error because of course a key can only be attached to one account.

How can I push/pull to and from both accounts with their respective GitHub credentials?

Twin answered 5/10, 2010 at 0:28 Comment(8)
The Steps given in the link http://net.tutsplus.com/tutorials/tools-and-tips/how-to-work-with-github-and-multiple-accounts worked well for me and ujust to add one thing you have to add you personal repo key also using<br> &nbsp; ssh-add ~/.ssh/id_rsa_COMPANY <br/> to tell the ssh-agent to include it for use.<hr/> Rest works fine for me with the above mentioned tutorial.Agleam
"because of course a key can be only attached to one account" of course? why?Piero
Git 2.13 onward supports conditional includes in .gitconfig which are a useful way to manage identities per folder hierarchy. https://mcmap.net/q/14313/-use-a-different-user-email-and-user-name-for-git-config-based-upon-remote-clone-urlGutshall
Possible duplicate of Multiple GitHub Accounts & SSH ConfigSavagism
Is there a technical or security reason to actually use different SSH keys for different accounts? I just use the same key set for all accounts (from the same device). The public key alone isn't enough to duplicate your identity, correct? When authenticating, your private key is never shared, it remains secret.Cornwell
Just use https?Hodge
The reason I say that is because even if you manage to setup 2 ssh keys in your gitconfig, you're still likely going to run into problems with credentials caching. You can circumvent all that by just using httpsHodge
GCM - Git Credential Manager 2.2.0 from June 2023 does support multiple users.Nathanaelnathanial
T
597

All you need to do is configure your SSH setup with multiple SSH keypairs.

Relevant steps from the first link:

  1. Generate an SSH-key:

    ssh-keygen -t ed25519 -C "[email protected]"
    

    Follow the prompts and decide a name, e.g. id_ed25519_example_company.

  2. Copy the SSH public-key to GitHub from ~/.ssh/id_ed25519_doe_company.pub and tell ssh about the key:

    ssh-add ~/.ssh/id_ed25519_doe_company
    
  3. Create a config file in ~/.ssh with the following contents:

    Host github-doe-company
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_doe_company
    
  4. Add your remote:

    git remote add origin git@github-doe-company:username/repo.git
    

    or change using:

    git remote set-url origin git@github-doe-company:username/repo.git
    

Also, if you're working with multiple repositories using different personas, you need to make sure that your individual repositories have the user settings overridden accordingly:

Setting user name, email and GitHub token – Overriding settings for individual repos https://help.github.com/articles/setting-your-commit-email-address-in-git/

Note: Some of you may require different emails to be used for different repositories, from git 2.13 you can set the email on a directory basis by editing the global config file found at: ~/.gitconfig using conditionals like so:

[user]
    name = Default Name
    email = [email protected]

[includeIf "gitdir:~/work/"]
    path = ~/work/.gitconfig

And then your work-specific config ~/work/.gitconfig would look like this:

[user]
    name = Pavan Kataria
    email = [email protected]

Thank you @alexg for informing me of this in the comments.

Triphylite answered 5/10, 2010 at 0:37 Comment(13)
Another useful link: gist.github.com/jexchan/2351996 (along with the first comment there).Counterattraction
This one is great code.tutsplus.com/tutorials/…Adna
Doesn't work. Nothing I have followed online works for Windows. Why is this so complicated?Venetis
Ok I managed to figure it out. Anyone using Windows cannot get ssh-add to work has to start the ssh-agent first by using the following command: eval 'ssh-agent -s'Venetis
Important caveat you may want to add in: If your email is different, any commits you push will still show up as being committed by your email that is set in .gitconfig. The solution is either to git config user.email [email protected], which changes it locally for that particular Git repo, OR you can use conditionals to automatically change your config'd email depending on what folder you are in. Source and how-to: https://mcmap.net/q/14119/-can-i-specify-multiple-users-for-myself-in-gitconfigVergos
Your first link talks about a /config file & you the mention a .gitconfig file. I assume the first link is out of date?Submerse
Additional note to the answer, if you had Host * at the first of the config file which also specifies an IdentifyFile. It will be used before all other github settings below it. This took me hours to figure out.Menken
This includeIf command just helped me a lot. It may be worth noting in your answer you can avoid all the host stuff by setting [core] sshCommand = ssh -i ~/.ssh/personal-github-ssh-key -o 'IdentitiesOnly=yes' -F /dev/nullTelescopy
Just want to point out the name in the Host is completely different from the HostName entry. The Host can be any value, and that should correspond to the value after the @ symbol in your git clone command.Hodge
For example, as in the answer above, when the Host is github-doe-company, git will still hit github.com because of the HostName entry listing github.com. The command to clone using the github-doe-company would be git clone git@github-doe-company:GithubComUserName/RepoName.gitHodge
To be safe, I'd recommend in addition to this, commenting out the key entry for the one you're not using at the momentHodge
As a note to myself, I found out after asking ChatGPT that if we use a pass phrase we will need to enter it every time we do any action and it is only insecure to not use a pass phrase if our machine is insecure, as someone can get access only if they have the key (if there is pass phrase they will need both the key and pass phrase)Hadst
This is lot of work so I created new user account on windows. May be not relevant, but a valid option.Serra
A
287

Use HTTPS

change remote url to https:

git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

and you are good to go:

git push

When you first enter your password, you will probably see this message:

Support for password authentication was removed on August 13, 2021.

You must use a Github PAT to do HTTPS pushes on github.com

Your PAT will look like a 40 character letter/number hash, like

zIa03uTnN0TTaReAALT09K33NMBbCfum6lw8TDSb

When you push using this method, you will be presented with a dialog box when you push:

Github enter password PAT dialog on Windows 10

To ensure that the commits appear as performed by USERNAME, one can setup the user.name and user.email for this project, too:

git config user.name USERNAME
git config user.email [email protected]
Actinomycete answered 10/12, 2014 at 17:25 Comment(7)
This solution provides the simplest method as I did not want to add more ssh keys. Just a note, if you already set your user.name and user.email with the --global flag, just do what he says above to set it locally for just that one repo. That solved a lot of trouble. Now to delete the old repo....Conflict
What about ssh or git protocol instead of https?Pneumograph
Support for password authentication was removed on August 13, 2021.Barter
thanks, this answer is easy to follow and does what you need with help of Personal-Access-Token as support for password authentication is removed.Hinder
Just a note: this method can give you the error "remote: Invalid username or password.". In this case, you'll need to use a token (github.com/settings/tokens/) instead of the username in the origin URL.Kristikristian
just use personal access token (create from github settings) in the password.Guerin
This solution is better. And you can use the accepted answer’s gitconfig file for commits.Hadst
S
174

Getting into shape

To manage a git repo under a separate github/bitbucket/whatever account, you simply need to generate a new SSH key.

But before we can start pushing/pulling repos with your second identity, we gotta get you into shape – Let's assume your system is setup with a typical id_rsa and id_rsa.pub key pair. Right now your tree ~/.ssh looks like this

$ tree ~/.ssh
/Users/you/.ssh
├── known_hosts
├── id_rsa
└── id_rsa.pub

First, name that key pair – adding a descriptive name will help you remember which key is used for which user/remote

# change to your ~/.ssh directory
$ cd ~/.ssh

# rename the private key
$ mv id_rsa github-mainuser

# rename the public key
$ mv id_rsa.pub github-mainuser.pub

Next, let's generate a new key pair – here I'll name the new key github-otheruser

$ ssh-keygen -t rsa -b 4096 -f ~/.ssh/github-otheruser

Now, when we look at tree ~/.ssh we see

$ tree ~/.ssh
/Users/you/.ssh
├── known_hosts
├── github-mainuser
├── github-mainuser.pub
├── github-otheruser
└── github-otheruser.pub    

Next, we need to setup a ~/.ssh/config file that will define our key configurations. We'll create it with the proper owner-read/write-only permissions

$ (umask 077; touch ~/.ssh/config)

Open that with your favourite editor, and add the following contents

Host github.com
  User git
  IdentityFile ~/.ssh/github-mainuser

Host github.com-otheruser
  HostName github.com
  User git
  IdentityFile ~/.ssh/github-otheruser

Presumably, you'll have some existing repos associated with your primary github identity. For that reason, the "default" github.com Host is setup to use your mainuser key. If you don't want to favour one account over another, I'll show you how to update existing repos on your system to use an updated ssh configuration.


Add your new SSH key to github

Head over to github.com/settings/keys to add your new public key

You can get the public key contents using: copy/paste it to github

$ cat ~/.ssh/github-otheruser.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDBVvWNQ2nO5...

Now your new user identity is all setup – below we'll show you how to use it.


Getting stuff done: cloning a repo

So how does this come together to work with git and github? Well because you can't have a chicken without and egg, we'll look at cloning an existing repo. This situation might apply to you if you have a new github account for your workplace and you were added to a company project.

Let's say github.com/someorg/somerepo already exists and you were added to it – cloning is as easy as

$ git clone github.com-otheruser:someorg/somerepo.git

That bolded portion must match the Host name we setup in your ~/.ssh/config file. That correctly connects git to the corresponding IdentityFile and properly authenticates you with github


Getting stuff done: creating a new repo

Well because you can't have a chicken without and egg, we'll look at publishing a new repo on your secondary account. This situation applies to users that are create new content using their secondary github account.

Let's assume you've already done a little work locally and you're now ready to push to github. You can follow along with me if you'd like

$ cd ~
$ mkdir somerepo
$ cd somerepo
$ git init

Now configure this repo to use your identity

$ git config user.name "Mister Manager"
$ git config user.email "[email protected]"

Now make your first commit

$ echo "hello world" > readme
$ git add .
$ git commit -m "first commit"

Check the commit to see your new identity was used using git log

$ git log --pretty="%H %an <%ae>"
f397a7cfbf55d44ffdf87aa24974f0a5001e1921 Mister Manager <[email protected]>

Alright, time to push to github! Since github doesn't know about our new repo yet, first go to github.com/new and create your new repo – name it somerepo

Now, to configure your repo to "talk" to github using the correct identity/credentials, we have add a remote. Assuming your github username for your new account is someuser ...

$ git remote add origin github.com-otheruser:someuser/somerepo.git

That bolded portion is absolutely critical and it must match the Host that we defined in your ~/.ssh/config file

Lastly, push the repo

$ git push origin master

Update an existing repo to use a new SSH configuration

Say you already have some repo cloned, but now you want to use a new SSH configuration. In the example above, we kept your existing repos in tact by assigning your previous id_rsa/id_rsa.pub key pair to Host github.com in your SSH config file. There's nothing wrong with this, but I have at least 5 github configurations now and I don't like thinking of one of them as the "default" configuration – I'd rather be explicit about each one.

Before we had this

Host github.com
  User git
  IdentityFile ~/.ssh/github-mainuser

Host github.com-otheruser
  HostName github.com
  User git
  IdentityFile ~/.ssh/github-otheruser

So we will now update that to this (changes in bold)

Host github.com-mainuser
  HostName github.com
  User git
  IdentityFile ~/.ssh/github-mainuser

Host github.com-otheruser
  HostName github.com
  User git
  IdentityFile ~/.ssh/github-otheruser

But now any existing repo with a github.com remote will not work with this identity file. But don't worry, it's a simple fix.

To update any existing repo to use your new SSH configuration, update the repo's remote origin field using set-url -

$ cd existingrepo
$ git remote set-url origin github.com-mainuser:someuser/existingrepo.git

That's it. Now you can push/pull to your heart's content


SSH key file permissions

If you're running into trouble with your public keys not working correctly, SSH is quite strict on the file permissions allowed on your ~/.ssh directory and corresponding key files

As a rule of thumb, any directories should be 700 and any files should be 600 - this means they are owner-read/write-only – no other group/user can read/write them

$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/config
$ chmod 600 ~/.ssh/github-mainuser
$ chmod 600 ~/.ssh/github-mainuser.pub
$ chmod 600 ~/.ssh/github-otheruser
$ chmod 600 ~/.ssh/github-otheruser.pub

How I manage my SSH keys

I manage separate SSH keys for every host I connect to, such that if any one key is ever compromised, I don't have to update keys on every other place I've used that key. This is like when you get that notification from Adobe that 150 million of their users' information was stolen – now you have to cancel that credit card and update every service that depends on it – what a nuisance.

Here's what my ~/.ssh directory looks like: I have one .pem key for each user, in a folder for each domain I connect to. I use .pem keys to so I only need one file per key.

$ tree ~/.ssh
/Users/myuser/.ssh
├── another.site
│   ├── myuser.pem
├── config
├── github.com
│   ├── myuser.pem
│   ├── someusername.pem
├── known_hosts
├── somedomain.com
│   ├── someuser.pem
└── someotherdomain.org
     └── root.pem

And here's my corresponding /.ssh/config file – obviously the github stuff is relevant to answering this question about github, but this answer aims to equip you with the knowledge to manage your ssh identities on any number of services/machines.

Host another.site
  User muyuser
  IdentityFile ~/.ssh/another.site/muyuser.pem

Host github.com-myuser
  HostName github.com
  User git
  IdentityFile ~/.ssh/github.com/myuser.pem

Host github.com-someuser
  HostName github.com
  User git
  IdentityFile ~/.ssh/github.com/someusername.pem

Host somedomain.com
  HostName 162.10.20.30
  User someuser
  IdentityFile ~/.ssh/somedomain.com/someuser.pem

Host someotherdomain.org
  User someuser
  IdentityFile ~/.ssh/someotherdomain.org/root.pem

Getting your SSH public key from a PEM key

Above you noticed that I only have one file for each key. When I need to provide a public key, I simply generate it as needed.

So when github asks for your ssh public key, run this command to output the public key to stdout – copy/paste where needed

$ ssh-keygen -y -f someuser.pem
ssh-rsa AAAAB3NzaC1yc2EAAAA...

Note, this is also the same process I use for adding my key to any remote machine. The ssh-rsa AAAA... value is copied to the remote's ~/.ssh/authorized_keys file


Converting your id_rsa/id_rsa.pub key pairs to PEM format

So you want to tame you key files and cut down on some file system cruft? Converting your key pair to a single PEM is easy

$ cd ~/.ssh
$ openssl rsa -in id_rsa -outform pem > id_rsa.pem

Or, following along with our examples above, we renamed id_rsa -> github-mainuser and id_rsa.pub -> github-mainuser.pub – so

$ cd ~/.ssh
$ openssl rsa -in github-mainuser -outform pem > github-mainuser.pem

Now just to make sure that we've converted this correct, you will want to verify that the generated public key matches your old public key

# display the public key
$ cat github-mainuser.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA ... R++Nu+wDj7tCQ==

# generate public key from your new PEM
$ ssh-keygen -y -f someuser.pem
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA ... R++Nu+wDj7tCQ==

Now that you have your github-mainuser.pem file, you can safely delete your old github-mainuser and github-mainuser.pub files – only the PEM file is necessary; just generate the public key whenever you need it ^_^


Creating PEM keys from scratch

You don't need to create the private/public key pair and then convert to a single PEM key. You can create the PEM key directly.

Let's create a newuser.pem

$ openssl genrsa -out ~/.ssh/newuser.pem 4096

Getting the SSH public key is the same

$ ssh-keygen -y -f ~/.ssh/newuser.pem
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACA ... FUNZvoKPRQ==
September answered 24/3, 2017 at 21:23 Comment(10)
I understand this is an old question but that doesn't excuse the fact that almost every answer here depends a link to some tutorial and is therefore subject to link rot. It's fine to link sources/citations, but you cannot lean on a link if you do not summarise the critical bits in your answer posted here.September
I upvoted your excellent and detailed answer as its clearly the correct way to do it. My issue with it is that its complex, and after a few years of using some accounts, I get a new one, then cannot recall how to do it "the right way". My way below is very simple - I just create 3 new files and one new script, and I'm good to go. Its worked flawlessly for me for many years. Readers can decide what works best for them.Metathesis
DavidH I appreciate the remark. The answer does feel complex if you take it as a whole, but the reader really only needs to concern his/herself with a small portion of the answer if their only goal is to add one other github identity – all of the remaining portions of the answer are aimed at setting you up with a robust solution for managing SSH keys in general, and are completely optional.September
I think git clone github.com-otheruser:someorg/somerepo.git needs to be git clone [email protected]:someorg/somerepo.git (adding the git@). Leastways, that's what I needed.Jubilation
@Jubilation all command line options, like specifying the user, can be done in the SSH config as well. For example: Host github.com (newline) User git (newline) IdentityFile ...September
The explanation was clear and easy to follow! many many thanks!Majunga
Cool answer, but it has no recommendation what to do when those identities are offered via ssh-agent remotely. So, what I need is to choose the key either by existing file or by fingerprint from the agent. Is it achievable?Pneumograph
Upvoted because it had a key piece of information missing from all other explanations, which is you must clone using the same identity you wish to push with.Foliaceous
@BrianCragun yep that's the key. If you forget to do that, you can always update the origin in your .git/config file ^^September
This is great answer, very detailed and easy to read. Thank you so much!Wingfooted
M
26

By creating different host aliases to github.com in your ~/.ssh/config, and giving each host alias its own ssh key, you can easily use multiple github accounts without confusion. That’s because github.com distinguishes not by user, which is always just git, but by the ssh key you used to connect. Just configure your remote origins using your own host aliases.”

The above summary is courtesy of comments on the blog post below.

I've found this explanation the clearest. And it works for me, at least as of April 2012.

http://net.tutsplus.com/tutorials/tools-and-tips/how-to-work-with-github-and-multiple-accounts/

Mudstone answered 10/4, 2012 at 16:30 Comment(1)
You will probably also need to run $ ssh-add ~/.ssh/id_rsa_COMPANY - see Error: Permission denied (publickey) - User DocumentationShoveler
C
25

The details at http://net.tutsplus.com/tutorials/tools-and-tips/how-to-work-with-github-and-multiple-accounts/ linked to by mishaba work very well for me.

From that page:

$ touch ~/.ssh/config

Then edit that file to be something like this (one entry per account):

#Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

Host github-COMPANY
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_COMPANY
Congregate answered 12/5, 2012 at 12:6 Comment(10)
i would also note that either "github.com" or "github-COMPANY" would need to be used when doing a clone (and probably other commands) like git clone git@github-COMPANY/repo/name.git to get the correct ssh key.Mchenry
@dtan: How would I implement this if I had to clone over https? git clone https://github-COMPANY/GitUserName/projectname.git doesn't seem to work. The default key using github.com works just fine.Lonergan
@IsaacRemuant, do you absolutely have to go over https? Every time you want to pull/push you have to input your user credentials. it would be best if you could do git://github-COMPANY...projectname.git. is there any error messaging for the https call?Mchenry
@dtan: I've had some issues with port 22 despite apparently having been opened for me. ssh: connect to host github.com port 22: Bad file number fatal: The remote end hung up unexpectedly. https was the only way so far. $ git clone https://github-USER/UserName/test_project_user.git Cloning into test_project_user... error: Couldn't resolve host 'github-USER' while accessing https://github-USER/N UserName/test_project_user.git/info/refs fatal: HTTP request failed I'm not sure wether it can be related to the config file or the way in which I'm trying to emulate your git call with https.Lonergan
Ultimately, I'll do an in depth analysis trying everything and post it appropriately as a question.Lonergan
@IsaacRemuant - have you tried debugging your ssh connection as outlined here: help.github.com/articles/generating-ssh-keys and here: help.github.com/articles/error-permission-denied-publickey. I have my Host set as qualifed uri, but I just changed it to something arbitrary like github-personal and it still worked for me fine:Mchenry
~$ ssh -T [email protected] Hi company_github_name! You've successfully authenticated, but GitHub does not provide shell access. ~$ ssh -T [email protected] Hi dtan! You've successfully authenticated, but GitHub does not provide shell access. after changing dtan.github.com to dtan-github: ~$ ssh -T git@dtan-github Hi dtan! You've successfully authenticated, but GitHub does not provide shell access. - meh stupid formatting...but you get the ideaMchenry
@dtan: Quite I delay in answering. I know. I wanted to do in depth tests to understand the issue. I could successfully do it from a machine with no proxy but I kept having problems from one with a proxy. finally I just went with this github.com/blog/642-smart-http-support which works well enough not to give me any headaches (and I end up not using ssh keys at all so I avoid the whole switching in the config file)Lonergan
@IsaacRemuant For https, use https://[email protected]/USERNAME/PROJECTNAME.git (as one of the answers below says). It worked for me when ssh didn't.Counterattraction
github.com is a URL. If you're cloning over https, and you sub-in github-COMPANY, you're not going to be able to hit the repo on github.com that wayHodge
M
23

In my case, I have my work account in Git-Lab and my personal account in GitHub. My Git-Lab account was configured globally to be accessed from all directories in my laptop like this:

git config --global user.name WORK_USERNAME
git config --global user.email [email protected]

So if you're looking for a solution without using SSL, you can do it by using git init in an empty folder, and then insert your personal account credentials in that folder:

git config user.name PERSONAL_USERNAME
git config user.email [email protected]

Notice here --global is not set, because you only want your personal git to be accessed from there and not everywhere, so whatever inside that folder will have its git credentials connected to your personal account and outside of it will be connected to your work account.

After that, you can clone your repository like so git clone your_repo_link.git. Then a new window will popup and ask you to login with your github account.

To verify your process try git config --list inside the folder that you created, you should see both work and personal usernames and emails with their directories.

Outside that folder, if you run git config --list you should see your work username and email only.

That's it, hope this helps someone without configuring SSL.

Multiplicity answered 15/5, 2021 at 22:5 Comment(5)
Worked for me but i can't see the work username and email while doing config --list in the work directory, But i can see the correct remote origin address. In my case, I cloned a GitLab repository and while cloning, it prompted me to enter a username and password, so i think the correct <url> is sufficient for git to identify a GitLab or GitHub repository. Both the usernames and emails are different for GitLab and GitHub in my case.Runesmith
Just a clarification I did git init and configured name and email address and then i cloned the gitlab repo in the same directory but in a new folder. I was hoping I could see the local name and email address too in this new folder too but i didn't. On the other hand, I can see both global and local usernames in the parent folder.Runesmith
It should open a new git window asking for your credentials when you push your files inside your folder that has your personal username and email. as long as --global is not used in that folder. Your main work git account shouldn't be affected I thinkMultiplicity
Worked for me but I had to update the credentials inside the cloned repository as well.Matheson
this should be the best solution, all others are too complicatedViola
S
19
  • Generate ssh keys

    ssh-keygen -t ed25519 -C "your_email"
    
  • Copy the public key from .ssh folder and add to your git-repository account

  • Go to ~/.ssh

  • Create a file named config(have no extension )

  • Open config file & add below codes. (change according to your account)

  1. Account 1

        # account_1
        Host gitlab.com-account_1
        HostName gitlab.com
        User git
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/id_rsa_account_1
    
  2. Account 2

        # Account2
        Host gitlab.com-Account2
        HostName gitlab.com
        User git
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/id_rsa_Account2
    
  3. Account 3

        # Account_3
        Host github.com-Account3
        HostName github.com
        User git
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/id_rsa_Account_3
    
  • Add remote url as follows
  1. Account 1

         git remote add origin [email protected]_1:group_name/repo_name.git
    
  2. Account 2

         git remote add origin [email protected]:group_name/repo_name.git
    
  3. Account 3

         git remote add origin github.com-Account3:github_username/repo_name.git
    

Make sure that IdentityFile names are same as you created during ssh key generation.

Stroy answered 13/1, 2018 at 15:22 Comment(2)
Could you please explain why you use PreferredAuthentications publickey?Hetman
@OliverPearmain Here I tell ssh that our preferred method for authentication is publickey . You can use password in PreferredAuthentications but you may have to enter password for authentication.Stroy
A
12

This answer is for beginners (none-git gurus). I recently had this problem and maybe its just me but most of the answers seemed to require rather advance understanding of git. After reading several stack overflow answers including this thread, here are the steps I needed to take in order to easily switch between GitHub accounts (e.g. assume two GitHub accounts, github.com/personal and gitHub.com/work):

  1. Check for existing ssh keys: Open Terminal and run this command to see/list existing ssh keys ls -al ~/.ssh
    files with extension .pub are your ssh keys so you should have two for the personal and work accounts. If there is only one or none, its time to generate other wise skip this.

    - Generating ssh key: login to github (either the personal or work acc.), navigate to Settings and copy the associated email.
    now go back to Terminal and run ssh-keygen -t rsa -C "the copied email", you'll see:

    Generating public/private rsa key pair.
    Enter file in which to save the key (/.../.ssh/id_rsa):


    id_rsa is the default name for the soon to be generated ssh key so copy the path and rename the default, e.g. /.../.ssh/id_rsa_work if generating for work account. provide a password or just enter to ignore and, you'll read something like The key's randomart image is: and the image. done.
    Repeat this step once more for your second github account. Make sure you use the right email address and a different ssh key name (e.g. id_rsa_personal) to avoid overwriting.
    At this stage, you should see two ssh keys when running ls -al ~/.ssh again.
  2. Associate ssh key with gitHub account: Next step is to copy one of the ssh keys, run this but replacing your own ssh key name: pbcopy < ~/.ssh/id_rsa_work.pub, replace id_rsa_work.pub with what you called yours.
    Now that our ssh key is copied to clipboard, go back to github account [Make sure you're logged in to work account if the ssh key you copied is id_rsa_work] and navigate to
    Settings - SSH and GPG Keys and click on New SSH key button (not New GPG key btw :D)
    give some title for this key, paste the key and click on Add SSH key. You've now either successfully added the ssh key or noticed it has been there all along which is fine (or you got an error because you selected New GPG key instead of New SSH key :D).
  3. Associate ssh key with gitHub account: Repeat the above step for your second account.
  4. Edit the global git configuration: Last step is to make sure the global configuration file is aware of all github accounts (so to say).
    Run git config --global --edit to edit this global file, if this opens vim and you don't know how to use it, press i to enter Insert mode, edit the file as below, and press esc followed by :wq to exit insert mode:

    [inside this square brackets give a name to the followed acc.] name = github_username email = github_emailaddress [any other name] name = github_username email = github_email [credential] helper = osxkeychain useHttpPath = true

Done!, now when trying to push or pull from a repo, you'll be asked which GitHub account should be linked with this repo and its asked only once, the local configuration will remember this link and not the global configuration so you can work on different repos that are linked with different accounts without having to edit global configuration each time.

Alluvial answered 16/9, 2017 at 19:19 Comment(1)
They should allow tags for answers, this is for mac OS.Crusted
K
12

just figured this out for Windows, using credentials for each repo:

cd c:\User1\SomeRepo
git config --local credential.https://github.com.user1 user1
git config --local credential.useHttpPath true
git config --local credential.helper manager
git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

The format of credential.https://github.com. tells the credential helper the URL for the credential. The 'useHttpPath' tells the credential manager to use the path for the credential. If useHttpPath is omitted then the credential manager will store one credential for https://github.com. If it is included then the credential manager will store multiple credentials, which is what I really wanted.

Karajan answered 22/2, 2019 at 21:3 Comment(0)
M
10

I use shell scripts to switch me to whatever account I want to be "active". Essentially you start from a fresh start, get one account configured properly and working, then move the these files to a name with the proper prefix. From then on you can use the command "github", or "gitxyz" to switch:

# my github script
cd ~/.ssh

if [ -f git_dhoerl -a -f git_dhoerl.pub -a -f config_dhoerl ]
then
    ; 
else 
    echo "Error: missing new files"
    exit 1
fi 

# Save a copy in /tmp, just in case
cp id_rsa /tmp
cp id_rsa.pub /tmp
cp config /tmp
echo "Saved old files in /tmp, just in case"

rm id_rsa
rm id_rsa.pub
rm config
echo "Removed current links/files"

ln git_dhoerl id_rsa
ln git_dhoerl.pub id_rsa.pub
ln config_dhoerl config

git config --global user.email "dhoerl@<company>.com"
git config --global github.user "dhoerl"        
git config --global github.token "whatever_it_is"

ssh-add -D

I've had great luck with this. I also created a run script in Xcode (for you Mac users) so it would not build my project unless I had the proper setting (since its using git):

Run Script placed after Dependencies (using /bin/ksh as the shell):

if [ "$(git config --global --get user.email)" != "dhoerl@<company>.com" ]
then
    exit 1
fi

EDIT: added tests for new files existence and copying old files to /tmp to address comment by @naomik below.

Metathesis answered 4/3, 2012 at 3:41 Comment(3)
Be careful when posting copy and paste boilerplate/verbatim answers to multiple questions, these tend to be flagged as "spammy" by the community. If you're doing this then it usually means the questions are duplicates so flag them as such instead: stackoverflow.com/questions/7548158, stackoverflow.com/questions/3225862, stackoverflow.com/questions/7924937Freund
This is a nightmare. If someone were to run this script before understanding that their id_rsa and id_rsa.pub keys would be deleted, they could get locked out of the remote.September
@naomik updated the script to both check for new files first, and to save old files in /tmpMetathesis
S
8

Simpler and Easy fix to avoid confusion..

For Windows users to use multiple or different git accounts for different projects.

Following steps:
Go Control Panel and Search for Credential Manager. Then Go to Credential Manager -> Windows Credentials

Now remove the git:https//github.com node under Generic Credentials Heading

This will remove the current credentials. Now you can add any project through git pull it will ask for username and password.

When you face any issue with other account do the same process.

refer to image

Simpson answered 28/3, 2018 at 17:21 Comment(2)
I do not find this helpful and convenient as users have to provide id and pw every time they push or pull.Decile
It is so painful to do for someone who will work continuously on both accountNiki
P
7

There are plenty of answers explaining how to accomplish what you have asked but I'd like to offer a different perspective.

I think there's something to be said for keeping work and personal stuff separate from each other. It's pretty trivial to switch between user accounts on all operating systems so you could just create separate OS accounts for work and play and have different github accounts logged in in each.

Maintaining a clear separation of concerns can also...

  • prevent your work files becoming co-mingled with your personal files
  • reduce the risk of carrying out an action on the wrong resource
  • potentially confine security breaches to one set of accounts / credentials
Phillisphilly answered 8/9, 2021 at 12:21 Comment(2)
This seems heavy-handed for an individual to do rather than simply using the litany of Git provided tools for user/identity management. I, for one, have several different professional accounts and repositories as I am a member of several organizations, so it doesn't really make a lot of sense to me to spin up 2, 3, 4, 5 etc OS accounts simply to log into git from a different username. Its why git settings have a hierarchical structure. Its a technical tool, and understanding how it works can be hard but we should still encourage people to do it "the right way" rather than hacking around it.Connors
I have a bitbucket account for my job. But sometimes I contribute to an open source project (for my job) and it is hosted on GitHub (or literally anywhere else). Now I need two accounts / keys.Molal
R
5

I see a lot of possible workarounds here. As a quick fix, @Greg's one seems relatively easy. However, it's best to set up separate ssh keys for all different accounts in the long run. This video demonstrates it briefly. Here are the steps mentioned in that video blog.

Step 1 - Create a New SSH Key for a new account and save it in a separate file (e.g. ~/.ssh/id_rsa_new_account_name), not in the original file i.e. ~/.ssh/id_rsa

ssh-keygen -t rsa -C "your-email-address"

Step 2 - Attach the New Key

  • Next, login to your second GitHub account
  • Browse to Account Overview, and attach the new key ~/.ssh/id_rsa_new_account_name.pub within the SSH Public Keys section.
  • In the Terminal, tell SSH to add the new identity by typing ssh-add ~/.ssh/id_rsa_new_account_name. If successful, you'll see a response of Identity Added.

Step 3 - Create a Config File

touch ~/.ssh/config

And save the following contents into the file

#Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

#New Account
Host github-new-account-name
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_new_account_name

Step 4 - Try it Out Now every time you want to use the new account and the associated repo, type this for the respective repo

git remote add origin git@github-new-account-name:your-domain.com/your-repo.git
Rotifer answered 17/6, 2021 at 19:37 Comment(1)
The definitive answer. Thanks @Abu_Shoeb. It is recommended to use ed25519 keys instead of rsa ones. They are much shorter. ssh-keygen -t ed25519 -C "email" store the key at the same location (%userprofile%\.ssh for Windows) .Seeing
C
4

In case you don't want to mess with the ~/.ssh/config file mentioned here, you could instead run git config core.sshCommand "ssh -i ~/.ssh/custom_id_rsa" in the repo where you want to commit from a different account.

The rest of the setup is the same:

  1. Create a new SSH key for the second account with ssh-keygen -t rsa -f ~/.ssh -f ~/.ssh/custom_id_rsa

  2. Sign in to github with your other account, go to https://github.com/settings/keys , and paste the contents of ~/.ssh/custom_id_rsa.pub

  3. Make sure you're using SSH instead of HTTPS as remote url: git remote set-url origin [email protected]:upstream_project_teamname/upstream_project.git

Crossed answered 22/10, 2019 at 21:49 Comment(1)
Thanks! This is less complicated than the config tutorials. In my case the config file did not work anyway but this direct solution did. Upvote + comment so hopefully others will find this answer before giving up to read.Mellissamellitz
S
3

Beside of creating multiple SSH Keys for multiple accounts you can also consider to add collaborators on each project using the same account emails and store the password permanently.

#this store the password permanently
$ git config --global credential.helper wincred

I have setup multiple accounts with different emails then put the same user and email on each account as one of the collaborators. By this way I can access to all account without adding SSH Key, or switching to another username, and email for the authentication.

Sloth answered 10/4, 2016 at 4:59 Comment(1)
This is by far the most accesible one.Bengal
P
3

The easiest and straightforward approach (IMHO) - no config files not too much hassle

Just create another ssh key.

Let's say you have a new work GitHub account, just create a new key for it:

ssh-keygen -t rsa -C "email@work_mail.com" -f "id_rsa_work_user1"`

You need to run the above only once.

Now you should have the old one and the new one, to see them, run:

ls -al ~/.ssh

From now on, every time you want to switch between the two, just run:

ssh-add -D
ssh-add ~/.ssh/id_rsa_work_user1 #make to use this without the suffix .pub

In order the switch to the old one, run again:

 ssh-add -D
 ssh-add ~/.ssh/<previous id_rsa>
Potpourri answered 11/2, 2019 at 12:39 Comment(1)
The most simple solution!Astrogation
O
3

Got my private repo working using SSH key pairs. This was tested on git for Windows.

Source: https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

A. Generate public and private key pairs

  1. Start git bash
  2. Run ssh-keygen -t ed25519 -C "[email protected]"
  3. When you're prompted to "Enter a file in which to save the key," press Enter to accept the default.
  4. Press enter for a blank passphrase.
  5. Start the ssh agent: eval $(ssh-agent)
  6. Add private key to ssh agent and store the passphrase: ssh-add ~/.ssh/id_ed25519

B. Add SSH keys to GitHub account

  1. Copy the public key to the clipboard: clip < ~/.ssh/id_ed25519.pub
  2. On GitHub, go to Profile -> Settings -> SSH Keys -> New SSH Key
  3. Give a title. E.g. "Windows on MacBook Pro"
  4. Paste the key and hit "Add SSH Key".

C. Test SSH connection

  1. Enter: ssh -T [email protected]
  2. Hit "yes" for any warning message.
  3. It should show: "Hi username!..." indicating a successful test.

D. Setup local repository to use SSH keys

  1. Change email and user name:
git config user.email [email protected]
git config user.name github_username
  1. Update remote links to use git. First list remote URI's:
git remote -v
git remote set-url origin [email protected]:github_username/your-repo-name.git

E. Test

git remote show origin
Opossum answered 23/11, 2020 at 19:10 Comment(0)
J
2

I found this gem to be very useful: sshwitch

https://github.com/agush22/sshwitch
http://rubygems.org/gems/sshwitch

It helps to switch out ssh keys. Remember to back up everything first!

Also to make sure that commits have the correct email address associated with them, I made sure that the ~/.gitconfig file had the proper email address.

Jayme answered 3/9, 2013 at 2:2 Comment(0)
R
2

another easier way is using multiple desktop apps, like what i am doing, using account A on Github desktop, while using account B on Github Kraken

Reins answered 3/9, 2018 at 14:40 Comment(0)
D
2

Simple approach without dealing with SSH keypairs

Just change the user.name & user.email locally in the repo. to the ones you want to push to that repo with.

Example: I have a work account in gitlab having a project. After cloning this project/repo, in the terminal, I type out:

git config user.name "my-work-username"
git config user.email "my-work-email-id"

Now, say I've another personal project/repo in Gitlab that I want to associate with my personal account. Just like above, after cloning, I type:

git config user.name "my-personal-username"
git config user.email "my-personal-email-id"

Hope this helps. Upvote if it worked for you! :)

Duque answered 3/7, 2021 at 17:1 Comment(2)
Tried on GitHub. Doesnt work.Azurite
Whilst it is relatively trivial to set a different user.name and user.email for different repos on your local machine, it does not seem to resolve the problem that if you have a credential stored in Windows Credential Manager for git:https://github.com, you will get errors when trying to push to GitHub from a repo that uses a different account than the one stored in the credential manager. Apparently you can't have two entries in the credential manager for the same address. Personally, I just removed the credential and was then prompted to authenticate when i ran git push origin main.Estrous
T
2

just add this line in your fav editor and you are done for life

git remote set-url origin https://[email protected]/profile-name/repo-name
Tessin answered 14/12, 2021 at 14:22 Comment(0)
C
1

If you happen to have WSL installed you can have two seperate git accounts - one on WSL and one in windows.

Chopstick answered 29/1, 2019 at 2:32 Comment(0)
C
1

IntelliJ Idea has built-in support of that https://www.jetbrains.com/help/idea/github.html#da8d32ae

Confinement answered 12/9, 2019 at 15:16 Comment(0)
B
1

Personal Directory .gitconfig using a personal access token

If you do not want to modify your host file, use SSH keys, or setup a .gitconfig for each repo, then you may use a personal .gitconfig that you basically include from the root level config. Given an OSX directory structure like

# root level git config
~/.gitconfig

# your personal repos under some folder like
../personal/
../home/
~/Dropbox/

Add a .gitconfig in your personal folder, such as ~/Dropbox/.gitconfig

[user]
    email = [email protected]
    name = First Last
[credential]
    username = PersonalGithubUsername
    helper = osxkeychain

In your root level .gitconfig add an includeIf section to source your personal config whenever you are in your personal directory. Any settings there will override the root config as long as the includeIf comes after the settings you want to override.

[user]
    email = [email protected]
    name = "First Last"
[credential]
    helper = osxkeychain
[includeIf "gitdir:~/Dropbox/**"]
    path = ~/Dropbox/.gitconfig

Try pushing to your personal repo or pulling from your private repo

git push
# prompts for password

When prompted enter either your personal password or, better yet, your personal access token that you have created in your account developer settings. Enter that token as your password.

Assuming you are already using git-credential-osxkeychain, your personal credentials should be stored in your keychain, so two github entries will show up, but with different accounts.

OSX keychain 2 entires for Github

Bodywork answered 4/7, 2020 at 15:14 Comment(0)
W
1

Option 0: you dont want to mess around with OS settings.. you just want to commit to a different github account with a different public key for one repo.

solution:

  1. create the new key: ssh-keygen -t rsa -b 4096 -f ~/.ssh/alt_rsa

  2. add the key to the keyset: ssh-add -K ~/.ssh/alt_rsa

  3. copy and add the pub key to the github account: (see github instructions)

  4. test the key with github: ssh -i ~/.ssh/alt_rsa T [email protected]

  5. clone the repo using the git protocol (not HTTP): git clone git@github:myaccount...

  6. in the cloned repo:

    git config core.sshCommand "ssh -i ~/.ssh/alt_rsa -F /dev/null"
    git config user.name [myaccount]
    git config user.email [myaccount email]

  7. now you should be able to git push correctly without interferring with your everyday git account

Waldenburg answered 13/10, 2020 at 12:30 Comment(0)
Z
1

Manage multiple GitHub accounts on one Windows machine (HTTPS)

Let's say you previously use git on your machine and configure git global config file. To check it open the terminal and :

git config --global -e

It opens your editor, and you may see something like this:

[user]
    email = [email protected]
    name = Your_Name
...

And this is great because you can push your code to GitHub account without entering credentials every time. But what if it needs to push to repo from another account? In this case, git will reject with 403 err, and you must change your global git credentials. To make this comfortable lat set storing a repo name in a credential manager:

git config --global credential.github.com.useHttpPath true

to check it open config one more time git config --global -e you will see new config lines

[credential]
    useHttpPath = true
...

The is it. Now when you first time push to any account you will see a pop-up Screenshot_1

Enter specific for this repo account credentials, and this will "bind" this account for the repo. And so in your machine, you can specify as many accounts/repos as you want.

For a more expanded explanation you can see this cool video that I found on youtube: https://youtu.be/2MGGJtTH0bQ

Zola answered 3/1, 2021 at 13:19 Comment(0)
U
1

2023 Update:

You can use Github Desktop. Here you just have to clone the repository in your local and manage the code using Github Desktop.

Unless answered 2/1, 2023 at 6:29 Comment(0)
B
1

in your ~./gitconfig CAREFULLY add:

[url "[email protected]:{my_username}"]
  insteadOf = https://github.com/{my_username}
[url "[email protected]{-my_org_short}:{my_org_name}/"]
  insteadOf = https://github.com/{my_org_name}/
  insteadOf = [email protected]:{my_org_name}/

where {-my_org_short} is optional

you may play adding your org username instead of {my_org_name} in the url section depending on your github setup

more info at this link

Buddleia answered 30/5, 2023 at 16:24 Comment(0)
Y
0

Unlike other answers, where you need to follow few steps to use two different github account from same machine, for me it worked in two steps.

You just need to :

1) generate SSH public and private key pair for each of your account under ~/.ssh location with different names and

2) add the generated public keys to the respective account under Settings >> SSH and GPG keys >> New SSH Key.

To generate the SSH public and private key pairs use following command:

cd ~/.ssh
ssh-keygen -t rsa -C "[email protected]" -f "id_rsa_WORK"
ssh-keygen -t rsa -C "[email protected]" -f "id_rsa_PERSONAL"

As a result of above commands, id_rsa_WORK and id_rsa_WORK.pub files will be created for your work account (ex - git.work.com) and id_rsa_PERSONAL and id_rsa_PERSONAL.pub will be created for your personal account (ex - github.com).

Once created, copy the content from each public (*.pub) file and do Step 2 for the each account.

PS : Its not necessary to make an host entry for each git account under ~/.ssh/config file as mentioned in other answers, if hostname of your two accounts are different.

Yettie answered 13/6, 2018 at 18:13 Comment(2)
How do you switch between the two accounts at your local PC?Crusted
There is no need to switch. Whenever you clone a repo in local the account info will be saved by the git in your local repo. So whenever you do a git push or pull inside that local repo the above configuration will detect which account to consider.Yettie
L
0

You should and must not push to the project with some common credentials. Once starting on a new machine use the following steps to setup and use correctly your gitlab credentials:

  • create the pubic / private ssh keys on the machine
  • copy paste the public key to the gitlab/github ui interface ( anyone hinting how-to do via the cmd line gets a free beer ... )
  • make sure you clone the repo via the git and not http url
  • set the git alias to avoid constant typing of the same prefix to the git command
  • during git commit ALWAYS use the author and e-mail flags
  • use git as normal you would do it

All this as follows:

 # create the public / private key credentials on that specific machine
 ssh-keygen -t rsa -b 4096 -C "<<you>>@org.net" -f ~/.ssh/id_rsa.<<you>>.`hostname -s`

 # setup your public key in the gitlab ui 
 cat ~/.ssh/id_rsa.<<you>>.`hostname -s`

 # make sure you clone the repo via the git and not http url
 git clone [email protected]:org/some-repo.git

 # set the git alias to avoid constant typing of the repeating prefix to the git cmd
 alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.<<you>>.`hostname -s`" git'

 # during git commit ALWAYS use the author and e-mail flags
 git add --all ; git commit -nm "$git_msg" --author "YourFirstName YourLastName <[email protected]>"

 # use git as normal
 git fetch --all; git pull --all 
Lazulite answered 4/10, 2019 at 9:37 Comment(0)
N
0
  1. Navigate to the directory in which you want to push your changes to a different GitHub account.
  2. Create a new SSH key in your terminal/command line.

    ssh-keygen -t rsa -C “your-email-address”

  3. The following will then show:

    Generating public/private rsa key pair. Enter file in which to save the key (/home/your_username/.ssh/id_rsa):

Copy and paste the path followed by an identifiable name for the file:

/home/your_username/.ssh/id_rsa_personal

4) It will then ask you for the following:

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

5) You can now type in the following command to see all the SSH keys you have on your local machine:

ls -al ~/.ssh

You should be able to see your new SSH key file. As you can see in my one I have both id_rsa_test and id_rsa_personal.pub.

drwx------  2 gmadmin gmadmin 4096 Nov 16 22:20 .
drwxr-xr-x 42 gmadmin gmadmin 4096 Nov 16 21:03 ..
-rw-------  1 gmadmin gmadmin 1766 Nov 16 22:20 id_rsa_personal
-rw-r--r--  1 gmadmin gmadmin  414 Nov 16 22:20 id_rsa_personal.pub
-rw-r--r--  1 gmadmin gmadmin  444 Nov  6 11:32 known_hosts

6) Next you need to copy the SSH key which is stored in id_rsa_personal.pub file. You can open this in text editor of your choice. I am currently using atom so I opened the file using the following command:

atom ~/.ssh/id_rsa_personal.pub

You will then get something similar to this:

ssh-rsa AAB3HKJLKC1yc2EAAAADAQABAAABAQCgU5+ELtwsKkmcoeF3hNd7d6CjW+dWut83R/Dc01E/YzLc5ZFri18doOwuQoeTPpmIRVDGuQQsZshjDrTkFy8rwKWMlXl7va5olnGICcpg4qydEtsW+MELDmayW1HHsi2xHMMGHlNv

7) Copy this and navigate to your GitHub account → Settings → SSH and GPG keys 8) Click on New SSH key. Copy the key, give it a title and add it. 9) Add key from terminal

ssh-add ~/.ssh/id_rsa_personal
Enter passphrase for /home/your_username/.ssh/id_rsa_personal: 

10) Configure user and password.

git config --global user.name "gitusername"
git config --global user.email "gitemail"

11) We are ready to commit and push now.

git init
git add .
git commit 
git push
Newsy answered 16/11, 2019 at 17:57 Comment(0)
C
0

If you have created or cloned another repository and you were not able to pull from origin or upstream adding the ssh key at that directory using the following command worked.

This is the error I was getting here:

Warning: Permanently added the RSA host key for IP address '61:fd9b::8c52:7203' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I used the following command, this works:

ssh-add ~/.ssh/id_rsa_YOUR_COMPANY_NAME

Cephalad answered 12/6, 2020 at 17:9 Comment(0)
A
0

Change the authentication method in github from SSh to HTTP. This way it will not care if you are logged with your work github account and you try to remotely interact with your personal github account (which has different credentials than the ones you are currently logged with onto your local machine).

Allowable answered 8/3, 2021 at 9:7 Comment(0)
D
0

There could be multiple way to do it but Following solution works for me and very simple. I am not trying to do it with SSH, my steps and solution is based on HTTPS.

  1. Create your project DIR on your local machine. Example d:\test_git_multiple_account

  2. go to the folder "test_git_multiple_account"

  3. Add few files here into the DIR

  4. Open Git bash here and run following command

    a. git init // initialization 
    b. git add , // add 
    c. git commit -m "initial commit"
        you will get following output : in my case i use to add one python file created 
        from code.
        **[master (root-commit) d4defd9] initial commit
        2 files changed, 4 insertions(+)
        create mode 100644 .vscode/settings.json
        create mode 100644 Hello.py**
    
    d.  git remote add origin <HTTPS repo link>
    e.  git remote -v // check the repo version 
    f.  git push origin master
        it will ask your git hub user name and password via popup screen. 
        you will get the following output 
        Counting objects: 100% (5/5), done.
        Delta compression using up to 4 threads
        Compressing objects: 100% (3/3), done.
        Writing objects: 100% (5/5), 411 bytes | 31.00 KiB/s, done.
        Total 5 (delta 0), reused 0 (delta 0), pack-reused 0
        remote:
        remote: Create a pull request for 'master' on GitHub by visiting:
        remote:      https://github.com/vishvadeepaktripathi/Hello_Py/pull/new/master
        remote:
        To https://github.com/vishvadeepaktripathi/Hello_Py.git
         * [new branch]      master -> master
    

This will create new branch as i named here called master. You can commit into main branch once you change the branch in this case your existing file will be delete. So i would recommend that to checkout into main branch into First step then proceed for every command in case you want to checkout directly into main branch. Caution At the First login it might give you an error message and ask again for login and password and then it will publish your change into Git hub.

Once this is done you will get message to new pull request into your github account. you can merge your changes from master branch to the main branch.

i created master branch here you named your branch as per your choice. Attaching the screen shot as well. enter image description here

Dolichocephalic answered 28/3, 2021 at 14:9 Comment(0)
P
0

Use docker!

This may not be suitable for everyone but this is what I ended up doing for myself.

All my developments are now done inside docker containers. I am a vim user but I know VSCode has plugin to work with docker containers.

So since I have different docker containers for different projects/languages, I can use different git configurations inside each. Problem solved.

Painkiller answered 5/7, 2021 at 18:31 Comment(0)
I
0

quickest solution would be configure one account on windows credential manager. lets suppose personal github account you can setup on your system with simplest flow which will be saved on windows credential manager/ global .gitconfig file and the other one you can connect on github desktop application.

Ivanna answered 8/4, 2023 at 17:9 Comment(0)
H
0

Use https for repository action using a secondary id

  1. Make a PAT

  2. Use the https versions of clone & push

In the following, your github.com sign in is GITHUBUSERNAME, and the repo you are operating on is REPONAME.

Clone

git clone https://github.com/GITHUBUSERNAME/REPONAME.git

Push

git push https://[email protected]/GITHUBUSERNAME/REPONAME.git

When you push using this method, you will be presented with a dialog box when you push:

github enter password PAT dialog

You have to enter your PAT that you created in step 1. Your PAT will look like a 40 character letter/number hash, like

zIa03uTnN0TTaReAALT09K33NMBbCfum6lw8TDSb

If you get the message

remote: Support for password authentication was removed on August 13, 2021.

You probably have a mistake in your PAT or you're trying to use the same password that you log into the website with. You can't use the password you log into github.com to push your commits. You have to use a PAT.

The only thing they need to do is 2FA for commits!!

Hodge answered 11/6, 2023 at 5:40 Comment(0)
K
0

For MacOS - Using gh CLI

Install gh CLI

 brew install gh

For MacOS, you don't need to run git config because GCM automatically configures Git for you.

When you need to switch the accounts you login

gh auth login

it will ask something similar to below

? What account do you want to log into? GitHub Enterprise Server
? GHE hostname: github.com
? You're already logged into github.com. Do you want to re-authenticate? Yes
? What is your preferred protocol for Git operations? HTTPS
? Authenticate Git with your GitHub credentials? Yes
? How would you like to authenticate GitHub CLI? Login with a web browser

! First copy your one-time code: XXXX-XXXX
Press Enter to open github.com in your browser...
✓ Authentication complete.
- gh config set -h github.com git_protocol https
✓ Configured git protocol
✓ Logged in as xxxx_xxxx

and then you clone / or do any other git operations as below

gh repo clone project/repo

Refer: https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git

Kaenel answered 14/6, 2023 at 6:28 Comment(0)
N
0

Another option is to use the latest Git Credential Manager (GCM).

In both cases, assuming the executable git-credential-manager is in your PATH:

git config --global credential.helper manager

The June 2023 GCM v2.2.0 officially supports multiple users

When you clone these repos, include the identity and an @ before the domain name in order to force Git and GCM to use different identities.
If you've already cloned the repos, you can update the remote URL to include the identity.

Example: fresh clones

# instead of `git clone https://example.com/open-source/library.git`, run:
git clone https://[email protected]/open-source/library.git

# instead of `git clone https://example.com/big-company/secret-repo.git`, run:
git clone https://[email protected]/big-company/secret-repo.git

Example: existing clones

# in the `library` repo, run:
git remote set-url origin https://[email protected]/open-source/library.git

# in the `secret-repo` repo, run:
git remote set-url origin https://[email protected]/big-company/secret-repo.git

See also PR 1267

Previously it was possible to use multiple accounts with GitHub, but this required prior knowledge about including the username in the remote URL (e.g. https://[email protected]/mona/test), and without this the incorrect account may be selected, and subsequently erased due to insufficient permissions.

This PR adds a few different features and prompts to improve discoverability and experience using multiple GitHub accounts with GCM:

  • Add login, logout and list commands for the GitHub provider
  • Add UI and TTY prompts to select between GitHub user accounts
  • Abridged documentation and links to quickly discover the 'user-in-remote-URL' functionality
  • (bonus!) Ability to suppress GUI prompts over text-based ones via the command-line using --no-ui

And:

You can use the github [list | login | logout] commands to manage your GitHub accounts.
These commands are documented in the [command-line usage][cli-usage] or by running git-credential-manager github --help.

Nathanaelnathanial answered 1/8, 2023 at 6:24 Comment(0)
M
0

Generate a Personal Access Token

  • Go to your GitHub account settings.
  • In the left sidebar, click on "Developer settings."
  • Click on "Personal access tokens."
  • Click on "Generate new token."
  • Give your token a descriptive name, select the scopes or permissions you'd like to grant this token, and then click "Generate token."
  • Important: Copy your new personal access token. You won’t be able to see it again!

Clone the Repository

  • Open Terminal on your Mac.

  • Use the git clone command with the repository URL and your personal access token. Replace <repository-url> with the URL of the repository and <your-token> with your personal access token.

    git clone https://<your-token>@github.com/username/repository.git
    
  • This will clone the repository using your personal access token for authentication.

Configure Git User

  • Use the cd command to navigate to the directory of the cloned repository.
    cd <repository-name>
    
  • If you haven't already, configure your Git user information for the current repository. This is important to ensure that your commits are associated with the correct user.
    git config user.email "[email protected]"
    git config user.name "Your Name"
    

Authenticate Git:

  • When you perform operations like pushing or pulling to/from the repository, Git will prompt you for your GitHub username (your email address associated with the account) and your personal access token as the password.

By following these steps, you should be able to clone a private repository from a different GitHub account and work with it on your Mac without disturbing your other GitHub account.

Maggy answered 24/3 at 16:49 Comment(0)
A
-1

You do not have to maintain two different accounts for personal and work. In fact, Github Recommends you maintain a single account and helps you merge both.

Follow the below link to merge if you decide there is no need to maintain multiple accounts.

https://help.github.com/articles/merging-multiple-user-accounts/

Alienism answered 1/5, 2018 at 22:14 Comment(0)
T
-1

Instead you just add your new email id to your personal git account. This way you don't need to add another SSH key. Just configure your new email by doing git config --global user.email newemail. Then you will be able to clone that repo.

Theomorphic answered 1/6, 2021 at 9:26 Comment(1)
no that won't work @jatin_verma. You cannot logon with multiple usernames to githubSeeing

© 2022 - 2024 — McMap. All rights reserved.