一键切换 Git 用户信息(Windows + macOS/Linux 双版本)

内容纲要

📌 写在前面

如果你在多个 Git 账号之间频繁切换,比如:

  • 私人 GitHub 账号
  • 公司 GitLab 账号
  • 团队的 Gitee 账号

每次都手动配置 user.nameuser.email,真的很烦人!

这篇文章介绍一种一键切换 Git 用户信息的方法,分别适配:

  • Windows:通过 .bat 脚本切换
  • macOS / Linux:通过 .sh 脚本切换

简单、清爽、优雅!


🎯 场景说明

假设你有两个 Git 身份需要切换:

场景 user.name user.email
个人开发 YourName yourname@example.com
公司项目 company_dev dev@company.com

我们分别用两种脚本,在两个系统下实现一键切换。


🪟 Windows 用户:使用 .bat 脚本

脚本内容:switch_git_user.bat

@echo off
echo 请选择要切换的 Git 用户:
echo 1. 个人账号 (yourname@example.com)
echo 2. 公司账号 (dev@company.com)
set /p choice=请输入数字 (1 或 2):

if "%choice%"=="1" (
    git config --global user.name "YourName"
    git config --global user.email "yourname@example.com"
    echo ✅ 已切换为个人账号
) else if "%choice%"=="2" (
    git config --global user.name "company_dev"
    git config --global user.email "dev@company.com"
    echo ✅ 已切换为公司账号
) else (
    echo ❌ 无效的选择
)

pause

使用方法:

  1. 把上述代码保存为 switch_git_user.bat
  2. 双击运行,按提示输入数字即可完成切换!

🍎 macOS / 🐧 Linux 用户:使用 .sh 脚本

脚本内容:switch_git_user.sh

#!/bin/bash

echo "请选择要切换的 Git 用户:"
echo "1. 个人账号 (yourname@example.com)"
echo "2. 公司账号 (dev@company.com)"
read -p "请输入数字 (1 或 2): " choice

if [ "$choice" = "1" ]; then
  git config --global user.name "YourName"
  git config --global user.email "yourname@example.com"
  echo "✅ 已切换为个人账号"
elif [ "$choice" = "2" ]; then
  git config --global user.name "company_dev"
  git config --global user.email "dev@company.com"
  echo "✅ 已切换为公司账号"
else
  echo "❌ 无效的选择"
fi

使用方法:

  1. 把上述内容保存为 switch_git_user.sh
  2. 给文件加执行权限:chmod +x switch_git_user.sh
  3. 执行脚本:./switch_git_user.sh

✨ BONUS:每个项目使用不同 Git 身份(高级配置)

如果你不想手动切换,而是希望某个目录下自动使用特定身份,可以使用 Git 的 includeIf 功能。

示例(放到 ~/.gitconfig):

[includeIf "gitdir:~/Projects/personal/"]
    path = ~/.gitconfig-personal

[includeIf "gitdir:~/Projects/company/"]
    path = ~/.gitconfig-company

然后创建对应的配置文件:

  • ~/.gitconfig-personal 内容:
[user]
    name = YourName
    email = yourname@example.com
  • ~/.gitconfig-company 内容:
[user]
    name = company_dev
    email = dev@company.com

这样你进入对应的项目目录,Git 会自动加载对应的身份,再也不用手动切换啦!


🧠 总结

系统平台 切换方式 备注
Windows .bat 脚本 双击运行即可
macOS/Linux .sh 脚本 + 终端 执行脚本即可
高级用法 includeIf 不用手动切换

Git 配置其实不复杂,但频繁切换身份确实麻烦。一个小小的脚本,不仅提升效率,还能避免出错(比如用错邮箱、暴露隐私信息)。

希望这篇文章能帮到你!

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward