乐闻世界logo
搜索文章和话题

How do I push to GitHub under a different username?

1个答案

1

When using Git and GitHub for version control, you might need to push to GitHub with different usernames, especially when working on both personal and work projects. Here are several steps to configure and use different usernames:

1. Global and Local Configuration

Git allows you to set both global and local (repository-specific) configurations. Global configurations apply to all repositories on your system, while local configurations apply only to specific repositories.

Set Global Username:

bash
git config --global user.name "your_global_username"

Set Global Email:

bash
git config --global user.email "your_global_email@example.com"

Set Local Username:

Navigate to the specific project directory and use the following command:

bash
git config user.name "your_specific_username"

Set Local Email:

bash
git config user.email "your_specific_email@example.com"

2. Check Configuration

Before pushing, you can check your configuration:

Check Global Configuration:

bash
git config --global --list

Check Local Configuration:

bash
git config --list

3. Using SSH Keys

If you are using different GitHub accounts on the same device, you can use SSH keys to distinguish between them.

  • Generate SSH keys:
bash
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Follow the prompts and set different filenames for different accounts.

  • Add the generated public key (the .pub file) to the corresponding GitHub account.

  • In the ~/.ssh/config file, set different Host entries for different GitHub accounts:

bash
# Account 1 Host github.com-user1 HostName github.com User git IdentityFile ~/.ssh/id_rsa_user1 # Account 2 Host github.com-user2 HostName github.com User git IdentityFile ~/.ssh/id_rsa_user2
  • When using Git, specify which SSH configuration to use:
bash
git clone git@github.com-user1:username/repository.git

Example

Suppose I have two projects: one is a personal project, and the other is a work project. I can set my personal GitHub account information in the directory of my personal project:

bash
cd personal-project git config user.name "MyPersonalUsername" git config user.email "personal@example.com"

And in the directory of my work project, set my work account information:

bash
cd work-project git config user.name "MyWorkUsername" git config user.email "work@example.com"

This way, when pushing from the personal project directory, it uses my personal account information; when pushing from the work project directory, it uses my work account information.

With this method, I can ensure I use the correct identity in the right project and maintain clear separation between my personal and work commit histories.

2024年6月29日 12:07 回复

你的答案