一、为什么要做 Git 初始化配置?
新安装 Git 后,如果不做任何配置,会遇到几个典型问题:
- 提交代码时报错(缺少用户名/邮箱)
- 每次 push 都要输入账号密码
- 默认分支名不符合团队规范(如 master vs main)
因此,初始化配置是每个开发者的“标准动作”。
二、基础配置:用户名和邮箱
这是最重要的一步,每个 commit 都会带上你的身份信息。
git config --global user.name 你的名字
git config --global user.email 你的邮箱
作用
- 标识代码提交者
- 在 GitHub / GitLab 上关联你的账号
- 团队协作时用于追踪提交记录
三、凭证管理(避免重复输入密码)
默认情况下,使用 HTTPS 拉取/推送代码时,每次都会要求输入账号和密码(或 Token)。
不同操作系统的推荐方案如下:
1️⃣ macOS
git config --global credential.helper osxkeychain
特点:
- 凭证存储在系统钥匙串(Keychain)
- 自动填充账号密码
- 安全性高(加密存储)
2️⃣ Windows(推荐)
git config --global credential.helper manager
特点:
- 使用 Git Credential Manager
- 凭证存储在 Windows 凭据管理器(加密)
- 支持浏览器登录 GitHub(含 2FA)
一般 Git for Windows 已默认启用,无需手动配置
3️⃣ Linux
git config --global credential.helper cache
默认缓存 15 分钟,可以自定义:
git config --global credential.helper 'cache --timeout=3600'
⚠️ 不推荐方式(了解即可)
git config --global credential.helper store
问题:
- 凭证明文保存在
~/.git-credentials - 安全性较低
- 不适合公司或生产环境
四、GitHub 认证方式变化(重要)
需要注意的是,GitHub 已不再支持账号密码登录。
推荐两种方式:
✅ Personal Access Token(PAT)
使用 Token 替代密码:
- 用户名:GitHub 用户名
- 密码:Token
✅ SSH(更推荐)
生成密钥:
ssh-keygen -t ed25519 -C 你的邮箱
优点:
- 无需输入密码
- 更安全
- 更适合专业开发和自动化环境
五、其他推荐配置
1️⃣ 默认分支名
git config --global init.defaultBranch main
2️⃣ 彩色输出
git config --global color.ui auto
3️⃣ 编辑器(推荐 VS Code)
git config --global core.editor "code --wait"
4️⃣ 换行符处理(macOS / Linux)
git config --global core.autocrlf input
六、一键初始化配置模板
可以直接执行下面这组命令完成基础配置:
git config --global user.name 你的名字
git config --global user.email 你的邮箱
git config --global credential.helper osxkeychain # Windows 改为 manager
git config --global init.defaultBranch main
git config --global color.ui auto
git config --global core.autocrlf input
七、查看当前配置
git config --global --list
八、总结
新装 Git 后,建议至少完成以下三件事:
- 配置身份(user.name + user.email)
- 配置凭证管理(避免重复登录)
- 设置默认行为(分支名、换行符等)
如果你希望进一步提升开发体验,可以考虑使用 SSH 方式管理仓库,实现真正的免密码操作。