多用戶不一樣平臺下的 Git 設置

場景描述:平常工做中,公司使用一個基於 gitlab 搭建的 Git 服務,咱們本身寫的小項目可能放在 Github、Coding 等平臺上,不一樣平臺的帳戶不一樣,如何便攜的拉取、提交代碼,而不用每次輸入帳號、密碼呢?git

1. 拉取代碼

1.1. 方式一:用戶名&密碼

這種方式主要用於 HTTPS 協議。github

git clone https://用戶名:密碼@github.com/xxx.git

當用戶名是郵箱時,以下:shell

# 這裏的 %40 對應郵箱地址中的 @ 符號
git clone https://aaaa%40gmail.com:密碼@github.com/xxx.git

1.2. 方式二:SSH

這種方式主要用於 SSH 協議。vim

步驟:bash

  1. 生成對應 Git 的公私鑰服務器

    ssh-keygen -t rsa -C "email1@xxx.com」 -f ~/.ssh/github_rsa
    ssh-keygen -t rsa -C "email2@xxx.com」 -f ~/.ssh/coding_rsa
  2. 添加私鑰ssh

    ssh-add ~/.ssh/github_rsa
    ssh-add ~/.ssh/coding_rsa

    解決:Could not open a connection to your authentication agentide

    ssh-agent bash

    其它命令:gitlab

    # 查看私鑰列表
    $ ssh-add -l
    # 清空私鑰列表
    $ ssh-add -D
  3. 添加對應不一樣平臺的配置測試

    touch ~/.ssh/config
    vim ~/.ssh/config

    文件內容以下:

    # github
    Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/github_rsa
    
    # coding
    Host coding.net
    HostName coding.net
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/coding_rsa
  4. 將公鑰添加到服務器

    這裏以 Github 爲例,首先拷貝對應的公鑰。

    pbcopy < ~/.ssh/github_rsa.pub

    打開 https://github.com,找到設置中的 SSH and GPG keys,以下圖:

    其中

    • Title 設置一個當前公鑰的標識
    • Key 公鑰複製到這裏
  5. 測試鏈接

    ssh -T git@github.com
    Hi xxxxx! You've successfully authenticated, but GitHub does not provide shell access.

    測試 clone

    git clone git@xxx:xxx/demo.git

2. 提交代碼

提交代碼時,若是沒有設置當前項目對應 Git 的 nameemail,將提示以下信息:

git commit -m 'added file'

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: empty ident name (for <>) not allowed

此時,咱們須要使用如下命令,對當前項目添加本地設置:

# 注意,這裏省略了參數 --local ,是針對當前項目的本地設置
git config user.name "your git user name"
git config user.email "yout git user email"

也可使用以下命令查看設置結果:

# 查看本地設置
git config --list --local

# 查看全局設置
git config --list --global

再次從新提交代碼便可。

注意:若是已經在 Git 的全局設置中添加 nameemail,在提交時會直接使用全局設置,而不會出現上面的提示信息。而且,以後在倉庫中看到的提交人和郵箱也會是全局設置中的 nameemail, 因此必定要增長項目的本地設置,避免因使用默認全局設置而形成的提交信息混亂。

相關文章
相關標籤/搜索