1. Git 配置级别详解
Git 提供三个级别的配置,优先级从高到低为:
Local(本地配置)
- 作用范围:当前 Git 仓库
- 配置文件:
.git/config - 优先级:最高
- 适用场景:项目特定的配置
Global(全局配置)
- 作用范围:当前用户的所有 Git 仓库
- 配置文件:
~/.gitconfig(Linux/Mac)或C:\Users\用户名\.gitconfig(Windows) - 优先级:中等
- 适用场景:用户级别的默认配置
System(系统配置)
- 作用范围:系统所有用户的所有 Git 仓库
- 配置文件:
/etc/gitconfig(Linux/Mac)或 Git 安装目录下(Windows) - 优先级:最低
- 适用场景:系统级别的统一配置
查看配置指令:
# 查看所有配置(包含所有级别)
git config --list
# 查看指定级别的配置
git config --local --list # 本地配置
git config --global --list # 全局配置
git config --system --list # 系统配置
# 查看特定配置项
git config user.name # 查看最终生效的用户名
git config --global user.name # 查看全局用户名
git config --local user.name # 查看本地用户名
# 查看配置来源
git config --show-origin user.name
git config --show-scope user.name
设置配置指令:
# 设置本地配置(在当前仓库目录下执行)
git config [--local] user.name "yourname"
git config [--local] user.email "email@example.com"
# 设置全局配置
git config --global user.name "你的姓名"
git config --global user.email "your_email@example.com"
git config --global core.editor "code --wait" # 设置默认编辑器
# 设置系统配置(需要管理员权限)
sudo git config --system core.autocrlf true
# 常用配置项示例
git config --global alias.co checkout # 设置别名
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global init.defaultBranch main # 设置默认分支名
清空配置指令:
# 删除特定配置项
git config [--local] --unset user.name # 删除本地配置
git config --global --unset user.name # 删除全局配置
git config --system --unset user.name # 删除系统配置
# 清空所有配置(谨慎使用)
# 注意:这会删除对应配置文件的所有内容
2. 多平台 SSH 配置
在日常开发中,我们经常需要同时连接多个 Git 代码托管平台(如 GitHub、Gitee、GitLab 等)。通过 SSH 配置,可以实现:
-
密钥隔离:不同平台使用不同的密钥对
-
自动识别:根据仓库地址自动选择对应密钥
-
简化操作:使用别名替代完整地址
配置步骤
- 生成密钥对。为每个平台生成独立的密钥对:
# 为 GitHub 生成密钥
ssh-keygen -t rsa -C "your_email@example.com" -f ~/.ssh/github
# 为 Gitee 生成密钥
ssh-keygen -t rsa -C "your_email@example.com" -f ~/.ssh/gitee
# 查看生成的密钥文件
ls -la ~/.ssh/
# 应该看到:github, github.pub, gitee, gitee.pub
参数说明:
-t rsa:使用 RSA 算法
-b 4096:密钥长度 4096 位(更安全)
-C:注释信息,通常使用邮箱
-f:指定密钥文件路径和名称
- 配置 SSH Config
创建或编辑 ~/.ssh/config 文件:
# GitHub 配置
Host github.com
HostName github.com
User zhangsan
IdentityFile ~/.ssh/github
IdentitiesOnly yes
# Gitee 配置
Host gitee.com
HostName gitee.com
User zs
IdentityFile ~/.ssh/gitee
IdentitiesOnly yes
# Gitee 别名(可选)
Host gitee # 如果是别名的话,git@gitee.com要发生变化,类似git clone gitee:username/repo.git
HostName gitee.com
User zhangsan
IdentityFile ~/.ssh/gitee
IdentitiesOnly yes
配置项说明:
Host:匹配的主机名或别名
HostName:实际的主机地址
User:连接用户名
IdentityFile:私钥文件路径
IdentitiesOnly:只使用指定的密钥
-
添加公钥到代码平台(略)
-
测试连接
# 测试 GitHub 连接
ssh -T git@github.com
# 成功显示:Hi username! You've successfully authenticated...
# 测试 Gitee 连接
ssh -T git@gitee.com
# 成功显示:Hi username! You've successfully authenticated...
# 测试别名连接(如果配置了)
ssh -T gitee
8963

被折叠的 条评论
为什么被折叠?



