Git Switch Account in Local Repository

For past few months I’m pretty occupied to rebrand my personal page. Back to code again, learning new libraries, and etc. Until then I face this (title) issue, and find a fit answer is tricky. So, I decided to write it down in here after figure it out and it makes me easy to look back whenever I need 😁.

Let’s jump in the thang!

Prerequisite

  1. Open Terminal and go to ~/.ssh folder to generate new SSH by typing ssh-keygen and will show
Generating public/private rsa key pair.
$ Enter file in which to save the key (/user/home/.ssh/id_rsa):<insert ssh keygen name>

Don’t press Enter and insert your SSH Key name. If you press Enter then your SSH Key name will set default name as id_rsa which is might be already used as the old SSH Key name and the value will be replaced. To check on if your new SSH Key is generated type ls, will show like this

List of file in .ssh folder
List of file in .ssh folder
List of file in .ssh folder

2. Copy new SSH Key to Git Account, by opening file .pub file inside /.ssh folder.

Opening .pub file
Opening .pub file
Opening .pub file

And put it in the key area, depends on remote Git providers. In my case, I’m using GitLab.

Adding SSH Key in GitLab

Setup SSH config

$ touch config
$ nano config
or
$ vim config

Inside config file insert this following command. In this case I’m using GitLab for Git providers, and it’s changeable depends on Git providers you use.

# default account
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa
# work account-1
Host gitlab.com-work1
HostName gitlab.com
User git
IdentityFile ~/.ssh/ssh_work1

Accessing remote repository

$ git config user.email "your work/new email"
$ git config user.name "your name/alias"

Now that email and name will only work on your chosen local repository. And whenever you push an update in that project, it’ll show that (new) information. Time to clone or access remote repository using this command

$ git remote add origin git@gitlab.com-work1:repo-group/repo-name.git
or
$ git clone git@gitlab.com-work1:repo-group/repo-name.git

Host URL need to adjust as same as written in the ~/.ssh/config as you can see. If you already clone or add a remote repository, you can change Host URL in .git/config inside your local repository. You can also edit name or email for this local repository.

Vim mode to edit config file
Vim mode to edit config file
Editing .git/config using vim command

This config only works for particular local repository as you chosen. Calling it in your global config won’t show this information, unless you declare it globally.

All set and you good to go! Your private project Git information will not interfered with your work or other project 😎

Product Designer | Tech Hustler | and... whatever you call 🙈 | nurisanendita.com