Git 安装与配置
2026/3/20大约 10 分钟
Git 安装与配置
在各平台安装 Git 并进行最佳配置
安装 Git
Windows 安装
方式一:官方安装包(推荐)
- 访问 Git 官网 下载安装包
- 运行安装程序,按照向导进行安装
安装选项建议:
| 选项 | 建议 |
|---|---|
| Git Bash Here | ✅ 右键菜单添加 Git Bash |
| Git GUI Here | ✅ 右键菜单添加 Git GUI |
| Git LFS | ✅ 大文件支持 |
| 默认编辑器 | VS Code(推荐)/ Vim / Notepad++ |
| PATH 环境变量 | ✅ Git from the command line and also from 3rd-party software |
| HTTPS 传输后端 | ✅ Use the OpenSSL library |
| 行尾转换 | ✅ Checkout Windows-style, commit Unix-style line endings |
| 终端模拟器 | ✅ Use MinTTY(Git Bash 默认终端) |
| 默认分支名 | ✅ Override the default branch name: main |
方式二:使用包管理器
# 使用 Chocolatey
choco install git
# 使用 Scoop
scoop install git
# 使用 winget
winget install Git.Git
方式三:Git for Windows SDK
适合需要构建 Git 或 Git 工具的开发者:
# 下载 Git for Windows SDK
# https://github.com/git-for-windows/build-extra/releases
macOS 安装
方式一:Xcode Command Line Tools
# 在终端中运行
xcode-select --install
# 或者直接运行 git,会提示安装
git --version
方式二:Homebrew(推荐)
# 安装 Homebrew(如果没有)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安装 Git
brew install git
# 升级 Git
brew upgrade git
方式三:官方安装包
从 Git 官网 下载 .dmg 安装包。
Linux 安装
Debian/Ubuntu
sudo apt update
sudo apt install git
# 安装最新版本
sudo add-apt-repository ppa:git-core/ppa
sudo apt update
sudo apt install git
CentOS/RHEL/Fedora
# CentOS/RHEL 7
sudo yum install git
# CentOS/RHEL 8+ / Fedora
sudo dnf install git
# 安装最新版本(从源码编译)
sudo yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker
cd /usr/local/src
wget https://github.com/git/git/archive/v2.43.0.tar.gz
tar -zxf v2.43.0.tar.gz
cd git-2.43.0
make prefix=/usr/local all
sudo make prefix=/usr/local install
Arch Linux
sudo pacman -S git
openSUSE
sudo zypper install git
验证安装
# 查看版本
git --version
# 输出: git version 2.43.0
# 查看安装位置
which git # Linux/macOS
where git # Windows
Git 配置层级
Git 配置分为三个层级,优先级从高到低:
| 优先级 | 层级 | 配置文件位置 | 作用范围 |
|---|---|---|---|
| 高 | local | .git/config | 当前仓库 |
| 中 | global | ~/.gitconfig | 当前用户所有仓库 |
| 低 | system | /etc/gitconfig(Win: C:\Program Files\Git\etc\gitconfig) | 系统所有用户 |
查看配置命令:
git config --local --list # 仓库级
git config --global --list # 用户级
git config --system --list # 系统级
git config --list # 所有配置(合并后)
git config --list --show-origin # 显示配置来源
配置文件格式
# ~/.gitconfig 示例
[user]
name = Your Name
email = your.email@example.com
[core]
editor = code --wait
autocrlf = input
[alias]
st = status
co = checkout
br = branch
ci = commit
[color]
ui = auto
必备配置
用户信息配置
# 设置用户名(必须)
git config --global user.name "Your Name"
# 设置邮箱(必须)
git config --global user.email "your.email@example.com"
# 验证配置
git config user.name
git config user.email
重要:每次 Git 提交都会使用这些信息,它们会被永久嵌入到提交记录中。
默认编辑器
# VS Code
git config --global core.editor "code --wait"
# VS Code Insiders
git config --global core.editor "code-insiders --wait"
# Vim
git config --global core.editor "vim"
# Nano
git config --global core.editor "nano"
# Sublime Text (macOS)
git config --global core.editor "subl -n -w"
# Sublime Text (Windows)
git config --global core.editor "'C:/Program Files/Sublime Text/sublime_text.exe' -w"
# Notepad++ (Windows)
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
# Emacs
git config --global core.editor "emacs"
默认分支名
# 设置默认分支名为 main(推荐)
git config --global init.defaultBranch main
行尾处理
# Windows(检出时转 CRLF,提交时转 LF)
git config --global core.autocrlf true
# Linux/macOS(只在提交时转 LF)
git config --global core.autocrlf input
# 不进行转换
git config --global core.autocrlf false
# 推荐:使用 .gitattributes 文件进行更精细的控制
.gitattributes 文件
# 默认行为
* text=auto
# 强制 LF
*.sh text eol=lf
*.py text eol=lf
*.js text eol=lf
# 强制 CRLF
*.bat text eol=crlf
*.cmd text eol=crlf
# 二进制文件
*.png binary
*.jpg binary
*.gif binary
*.ico binary
*.pdf binary
*.zip binary
推荐配置
颜色配置
# 启用颜色输出
git config --global color.ui auto
# 详细颜色配置
git config --global color.branch.current "yellow reverse"
git config --global color.branch.local "yellow"
git config --global color.branch.remote "green"
git config --global color.diff.meta "yellow bold"
git config --global color.diff.frag "magenta bold"
git config --global color.diff.old "red bold"
git config --global color.diff.new "green bold"
git config --global color.status.added "green"
git config --global color.status.changed "yellow"
git config --global color.status.untracked "red"
合并与差异工具
# 设置差异工具
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'
# 设置合并工具
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait $MERGED'
# 不保留 .orig 备份文件
git config --global mergetool.keepBackup false
# 使用 P4Merge
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge $BASE $LOCAL $REMOTE $MERGED'
git config --global diff.tool p4merge
git config --global difftool.p4merge.cmd 'p4merge $LOCAL $REMOTE'
推送配置
# 推送当前分支到同名远程分支(推荐)
git config --global push.default current
# 其他选项:
# simple - 推送到跟踪的上游分支(默认)
# matching - 推送所有同名分支
# upstream - 推送到上游分支
# nothing - 禁用 push
# 推送时自动设置上游分支
git config --global push.autoSetupRemote true
拉取配置
# 拉取时使用变基而非合并(推荐用于保持线性历史)
git config --global pull.rebase true
# 保留合并提交
git config --global pull.rebase merges
# 如果有未提交的更改,先 stash
git config --global rebase.autoStash true
凭证存储
# macOS - 使用 Keychain
git config --global credential.helper osxkeychain
# Windows - 使用 Credential Manager
git config --global credential.helper manager
# Linux - 缓存凭证(默认 15 分钟)
git config --global credential.helper cache
# Linux - 缓存更长时间(1小时)
git config --global credential.helper 'cache --timeout=3600'
# 存储到文件(不推荐,明文存储)
git config --global credential.helper store
常用别名配置
基础别名
# 状态
git config --global alias.st status
git config --global alias.ss "status -s"
# 分支
git config --global alias.br branch
git config --global alias.co checkout
git config --global alias.sw switch
# 提交
git config --global alias.ci commit
git config --global alias.cm "commit -m"
git config --global alias.ca "commit --amend"
git config --global alias.can "commit --amend --no-edit"
# 添加
git config --global alias.aa "add --all"
git config --global alias.ap "add -p"
日志别名
# 简洁日志
git config --global alias.lg "log --oneline --graph --decorate"
# 详细日志
git config --global alias.ll "log --oneline --graph --decorate --all"
# 格式化日志
git config --global alias.lf "log --pretty=format:'%C(yellow)%h%Creset - %C(green)%an%Creset, %C(cyan)%ar%Creset : %s'"
# 最后一次提交
git config --global alias.last "log -1 HEAD --stat"
# 今天的提交
git config --global alias.today "log --since=midnight --author='$(git config user.email)' --oneline"
高级别名
# 撤销上次提交(保留修改)
git config --global alias.undo "reset HEAD~1 --mixed"
# 清理未跟踪文件
git config --global alias.clean-all "clean -fd"
# 显示别名列表
git config --global alias.aliases "config --get-regexp alias"
# 显示所有分支的最后提交
git config --global alias.branches "branch -a -v"
# 显示贡献者统计
git config --global alias.contributors "shortlog -sn"
# 快速暂存
git config --global alias.save "stash push -m"
git config --global alias.pop "stash pop"
# 查找包含特定内容的提交
git config --global alias.find "log --all --full-history --"
# 图形化历史
git config --global alias.graph "log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)'"
工作流别名
# 开始新功能
git config --global alias.feature "checkout -b feature/"
# 开始修复
git config --global alias.fix "checkout -b fix/"
# 同步主分支
git config --global alias.sync "!git fetch origin && git rebase origin/main"
# 完成功能并清理
git config --global alias.done "!git checkout main && git pull && git branch -d @{-1}"
SSH 密钥配置
生成 SSH 密钥
# 生成 Ed25519 密钥(推荐)
ssh-keygen -t ed25519 -C "your.email@example.com"
# 如果系统不支持 Ed25519,使用 RSA
ssh-keygen -t rsa -b 4096 -C "your.email@example.com"
# 指定文件名
ssh-keygen -t ed25519 -C "your.email@example.com" -f ~/.ssh/github_key
添加到 SSH Agent
# 启动 SSH Agent
eval "$(ssh-agent -s)"
# 添加私钥
ssh-add ~/.ssh/id_ed25519
# macOS:添加到 Keychain
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
# 列出已添加的密钥
ssh-add -l
SSH 配置文件
# ~/.ssh/config
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_key
AddKeysToAgent yes
# macOS
UseKeychain yes
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/gitlab_key
AddKeysToAgent yes
Host bitbucket.org
HostName bitbucket.org
User git
IdentityFile ~/.ssh/bitbucket_key
AddKeysToAgent yes
# 公司 GitLab
Host gitlab.company.com
HostName gitlab.company.com
User git
IdentityFile ~/.ssh/company_key
Port 2222
添加公钥到托管平台
# 复制公钥内容
# macOS
pbcopy < ~/.ssh/id_ed25519.pub
# Linux
xclip -sel clip < ~/.ssh/id_ed25519.pub
# Windows
clip < ~/.ssh/id_ed25519.pub
# 或者直接查看
cat ~/.ssh/id_ed25519.pub
然后在各平台的 SSH Keys 设置中添加:
- GitHub: Settings → SSH and GPG keys → New SSH key
- GitLab: Preferences → SSH Keys
- Gitee: 设置 → SSH 公钥
测试连接
# GitHub
ssh -T git@github.com
# 预期输出: Hi username! You've successfully authenticated...
# GitLab
ssh -T git@gitlab.com
# 预期输出: Welcome to GitLab, @username!
# Gitee
ssh -T git@gitee.com
# 预期输出: Hi username! You've successfully authenticated...
GPG 签名配置
安装 GPG
# macOS
brew install gnupg
# Ubuntu/Debian
sudo apt install gnupg
# Windows - 安装 Gpg4win
# https://www.gpg4win.org/
生成 GPG 密钥
# 生成密钥
gpg --full-generate-key
# 选项:
# 1. RSA and RSA (default)
# 2. 4096 bits
# 3. 密钥有效期(0 = 永不过期)
# 4. 输入姓名和邮箱
# 5. 设置密码
# 列出密钥
gpg --list-secret-keys --keyid-format=long
# 输出示例:
# sec rsa4096/3AA5C34371567BD2 2024-01-01 [SC]
# A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0
# uid [ultimate] Your Name <your.email@example.com>
# ssb rsa4096/4BB6D45482678CE3 2024-01-01 [E]
配置 Git 使用 GPG
# 获取密钥 ID(上面输出中 sec 行的 / 后面部分)
# 例如:3AA5C34371567BD2
# 配置 Git 使用该密钥
git config --global user.signingkey 3AA5C34371567BD2
# 默认对所有提交签名
git config --global commit.gpgsign true
# 默认对所有标签签名
git config --global tag.gpgsign true
# 指定 GPG 程序位置(如果需要)
git config --global gpg.program gpg
# Windows
git config --global gpg.program "C:/Program Files (x86)/GnuPG/bin/gpg.exe"
导出公钥
# 导出 ASCII 格式公钥
gpg --armor --export 3AA5C34371567BD2
# 保存到文件
gpg --armor --export 3AA5C34371567BD2 > public_key.asc
将公钥添加到 GitHub/GitLab 的 GPG Keys 设置中。
签名提交和标签
# 签名提交
git commit -S -m "Signed commit"
# 签名标签
git tag -s v1.0 -m "Signed tag"
# 验证签名
git log --show-signature
git verify-commit <commit>
git verify-tag <tag>
多账户配置
场景:公司和个人账户
# 目录结构
~/
├── work/ # 公司项目
│ └── project-a/
└── personal/ # 个人项目
└── project-b/
方法一:使用 includeIf
# ~/.gitconfig
[user]
name = Personal Name
email = personal@example.com
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
[includeIf "gitdir:~/personal/"]
path = ~/.gitconfig-personal
# ~/.gitconfig-work
[user]
name = Work Name
email = work@company.com
signingkey = WORK_GPG_KEY
[core]
sshCommand = ssh -i ~/.ssh/work_key
# ~/.gitconfig-personal
[user]
name = Personal Name
email = personal@example.com
signingkey = PERSONAL_GPG_KEY
[core]
sshCommand = ssh -i ~/.ssh/personal_key
方法二:仓库级配置
# 在每个仓库中单独配置
cd ~/work/project-a
git config user.name "Work Name"
git config user.email "work@company.com"
SSH 多账户配置
# ~/.ssh/config
# 个人 GitHub
Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/personal_github
# 工作 GitHub
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/work_github
# 克隆时使用对应的 host
git clone git@github.com-personal:username/repo.git
git clone git@github.com-work:company/repo.git
完整配置模板
~/.gitconfig 完整示例
[user]
name = Your Name
email = your.email@example.com
signingkey = YOUR_GPG_KEY
[core]
editor = code --wait
autocrlf = input
safecrlf = warn
whitespace = fix
pager = delta
excludesFile = ~/.gitignore_global
[init]
defaultBranch = main
[color]
ui = auto
[push]
default = current
autoSetupRemote = true
followTags = true
[pull]
rebase = true
[fetch]
prune = true
pruneTags = true
[rebase]
autoStash = true
autoSquash = true
[merge]
tool = vscode
conflictstyle = diff3
[mergetool "vscode"]
cmd = code --wait $MERGED
[diff]
tool = vscode
colorMoved = default
[difftool "vscode"]
cmd = code --wait --diff $LOCAL $REMOTE
[commit]
gpgsign = true
template = ~/.gitmessage
[tag]
gpgsign = true
[credential]
helper = osxkeychain
[alias]
# 状态
st = status
ss = status -s
# 分支
br = branch
co = checkout
sw = switch
# 提交
ci = commit
cm = commit -m
ca = commit --amend
can = commit --amend --no-edit
# 日志
lg = log --oneline --graph --decorate
ll = log --oneline --graph --decorate --all
last = log -1 HEAD --stat
# 差异
df = diff
dc = diff --cached
# 其他
undo = reset HEAD~1 --mixed
aliases = config --get-regexp alias
contributors = shortlog -sn
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
[filter "lfs"]
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
required = true
[url "git@github.com:"]
insteadOf = https://github.com/
~/.gitignore_global 全局忽略
# 操作系统文件
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Thumbs.db
ehthumbs.db
Desktop.ini
# 编辑器和 IDE
.idea/
.vscode/
*.swp
*.swo
*~
.project
.settings/
.classpath
*.sublime-project
*.sublime-workspace
# 日志和临时文件
*.log
*.tmp
*.temp
*.bak
*.backup
# 环境文件
.env
.env.local
.env.*.local
# 依赖目录
node_modules/
vendor/
__pycache__/
*.pyc
.gradle/
# 构建输出
dist/
build/
out/
target/
*.o
*.so
*.exe
~/.gitmessage 提交模板
# <type>(<scope>): <subject>
#
# <body>
#
# <footer>
# Type 类型:
# feat: 新功能
# fix: Bug 修复
# docs: 文档更新
# style: 代码格式(不影响功能)
# refactor: 重构(既不是新功能也不是修复)
# perf: 性能优化
# test: 测试相关
# chore: 构建过程或辅助工具变动
#
# Scope 范围:影响的模块/组件
#
# Subject 标题:
# - 使用祈使句
# - 首字母不大写
# - 结尾不加句号
# - 不超过 50 字符
#
# Body 正文:
# - 说明 what 和 why,而不是 how
# - 每行不超过 72 字符
#
# Footer 页脚:
# - 关联 Issue:Closes #123
# - 破坏性变更:BREAKING CHANGE: description
配置诊断与调试
查看配置
# 查看所有配置及来源
git config --list --show-origin
# 查看特定配置
git config --get user.email
# 查看特定配置及来源
git config --show-origin user.email
# 查看配置生效的范围
git config --show-scope user.email
调试配置问题
# 启用详细输出
GIT_TRACE=1 git status
# 调试 SSH
GIT_SSH_COMMAND="ssh -vvv" git fetch
# 调试凭证
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git push
重置配置
# 删除全局配置项
git config --global --unset user.name
# 删除整个配置节
git config --global --remove-section alias
# 编辑配置文件
git config --global --edit