切换GIT账号

使用新账号

配置新账号
  1. 切换账号、邮箱
bash 复制代码
#查看账号
git config --global user.name
git config --global user.email

#修改
git config --global user.name "新用户名"
git config --global user.email "新邮箱"

#指定项目中切换
git config user.name "新用户名"
git config user.email "新邮箱"
  1. 配置ssh-key
    a. 生成ssh-key
    b. gitlab 配置ssh-key: User Settings -> SSH Keys -> pub 中的内容粘贴进去
bash 复制代码
ssh-keygen -t ed25519 -C "新账号邮箱"
  1. 配置 ssh config
bash 复制代码
# 如果没有 config 文件,手动创建
vim ~/.ssh/config

Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_ed25519_new
  1. 测试
bash 复制代码
ssh -T git@gitlab.com
config 结构解析
bash 复制代码
Host gitlab-new
    HostName git.joyport.inout
    User git
    Port 2222
    IdentityFile ~/.ssh/id_rsa_new
    IdentitiesOnly yes
  1. Host gitlab-new → 你自己起的 alias 名
  2. HostName → 真实服务器
  3. Port → 2222
  4. IdentityFile → 新账号的私钥
  5. IdentitiesOnly yes → 强制只用这个 key
  6. 多账号共存时:Git 会尝试 key list,如果前面的key 被blocked掉,不会尝试后续的key

ssh-agent

使用方法
  1. ssh-agent:它负责把ssh 私钥加载到内存,不需要每次输入密码和重新读取key(从 id_ras 文件中读取)
    a. 启动:eval "$(ssh-agent -s)"
    b. 测试 agent:ssh-add -l
    c. 添加key:ssh-add ~/.ssh/id_ed25519_new
  2. eval "$(ssh-agent -s)"
windows
  1. Git for Windows 使用的是内置 ssh,不依赖ssh-agent
  2. Win10 自带的 OpenSSH Authentication Agent 服务,默认关闭,可以上面的"使用方法"手动打开

问题

配置了新的 ssh-key,并且 通过 gitconfig 修改了 username 和email,为什么还是使用旧账号的信息
  1. 原因:Git for Windows 默认使用 id_rsa
  2. 验证:
bash 复制代码
#执行
GIT_SSH_COMMAND="ssh -v" git pull
#输出
debug1: Trying private key: C:\\Users\\xxx\\.ssh\\id_rsa
debug1: Offering public key: id_rsa
  1. 解决:
bash 复制代码
-----------------------多账号-----------------------
*************修改config*************
# 项目中创建 /.ssh/config 文件
# 结构
project/
  .git/
  .ssh/
    config
# config 中写入
Host gitlab.com
    IdentityFile ~/.ssh/id_rsa_new
    User git
*************修改remote url*************
# 修改 ~/.ssh/config
Host gitlab-new
    HostName gitlab.com
    IdentityFile ~/.ssh/id_rsa_new
    User git
# 修改 remote url
git remote set-url origin git@gitlab-new:project.git

-----------------------全局 -----------------------
# 全局修改
~/.ssh/config
Host gitlab.com
    IdentityFile ~/.ssh/id_rsa_new
    User git
相关推荐
回家路上绕了弯8 小时前
Git worktree 终极指南:告别分支切换烦恼,实现多分支并行开发
git·后端
日更嵌入式的打工仔9 小时前
Git & TortoiseGit
git
会的越多不会的也就越多10 小时前
Win11 右键菜单优化指南:如何把 Git 功能“提”到一级菜单?
git
rebekk12 小时前
claude工作区与git仓库的关系
linux·git·python
神の愛12 小时前
GIT,可以参数这篇,需要加以理解,文字比较冗余,还请见谅
git
jolimark13 小时前
Windows下如何用GCC编译C语言?轻便方法分享
c语言·windows·git·mingw·gcc编译器
△曉風殘月〆13 小时前
一文带你掌握Visual Studio中集成的git功能
git·visual studio
不爱吃糖的程序媛14 小时前
鸿蒙三方库适配读懂 `thirdparty/AES/.gitignore`:哪些文件不该进 Git?
git·elasticsearch·harmonyos
天若有情6731 天前
【C++原创开源】formort.h:一行头文件,实现比JS模板字符串更爽的链式拼接+响应式变量
开发语言·javascript·c++·git·github·开源项目·模版字符串
海盗12341 天前
在群晖NAS上使用Git Server
git