How to fix "Permission denied (publickey)." error when pushing to Github (mac)

I was trying to push to Github from VSCode when I got the following error:

[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

I am not really sure what happened since I hadn't changed anything. The only thing I can think of is I installed SourceTree, but I don't remember messing with any of my settings. Anyways this is how I fixed this "Permission denied (publickey)" error.

  1. Open your terminal and do cd ~/.ssh.

  2. Type ls. You should see id_rsa and id_rsa.pub. My issue was that those files were not there anymore. To create those files, do step 3:

  3. Run: ssh-keygen -t rsa -C "[email protected]", replacing "[email protected]" with your actual email.

  4. Open the file id_rsa.pub. If you have VSCode, you can just do code id_rsa.pub (explained here), and it opens the file in VS Code. Otherwise, you can do vim id_rsa.pub. (you can exit out of vim by typing :q!).

  5. Copy everything you see (make sure you don't copy any extra spaces).

  6. Go to github.com -> Settings -> SSH and GPG Keys https://github.com/settings/keys. Click "New SSH Key". Give it a title and paste in the key. Finally, click "Add SSH Key".

  7. That's it. Try git push again, and it should work.

Want to learn how to code and make money online? Check out CodingPhase (referral link)