强曰为道

与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

02 - 安装配置:各平台安装、初始配置、SSH Key

第二章:安装配置

工欲善其事,必先利其器。正确的安装和配置是高效使用 Git 的前提。


2.1 各平台安装 Git

2.1.1 Linux

Debian / Ubuntu

# 更新包索引
$ sudo apt update

# 安装 Git
$ sudo apt install git

# 验证安装
$ git --version
git version 2.43.0

Fedora / RHEL / CentOS

# Fedora
$ sudo dnf install git

# RHEL / CentOS 8+
$ sudo dnf install git

# CentOS 7 (需要 IUS 源)
$ sudo yum install https://repo.ius.io/ius-release-el7.rpm
$ sudo yum install git242

Arch Linux

$ sudo pacman -S git

从源码编译(获取最新版)

# 安装依赖
$ sudo apt install libcurl4-gnutls-dev libexpat1-dev \
  gettext libz-dev libssl-dev

# 下载源码
$ wget https://github.com/git/git/archive/refs/tags/v2.45.0.tar.gz
$ tar -xzf v2.45.0.tar.gz
$ cd git-2.45.0

# 编译安装
$ make prefix=/usr/local all
$ sudo make prefix=/usr/local install

# 验证
$ git --version

2.1.2 macOS

# 方法 1:Xcode Command Line Tools(推荐)
$ xcode-select --install

# 方法 2:Homebrew
$ brew install git

# 方法 3:MacPorts
$ sudo port install git

# 验证
$ git --version

2.1.3 Windows

安装方式说明
Git for Windowsgit-scm.com 官方下载
WSL2wsl --install 后按 Linux 方式安装
Scoopscoop install git
Chocolateychoco install git
wingetwinget install Git.Git

Git for Windows 安装时的关键选项:

选项推荐选择说明
Default editorVS Code / Vim设置默认编辑器
PATH environmentGit from the command line添加到 PATH
SSH executableUse bundled Open SSH使用内置 SSH
Line ending conversionsCheckout as-is, commit Unix-style保持 LF 行尾
Terminal emulatorUse Windows’ default console使用默认终端

2.2 初始配置

Git 的配置分为三个层级:

层级配置文件命令参数作用范围
系统级/etc/gitconfig--system所有用户
用户级~/.gitconfig--global当前用户
仓库级.git/config--local当前仓库

💡 优先级:仓库级 > 用户级 > 系统级

2.2.1 必须配置项

# 设置用户名(显示在提交记录中)
$ git config --global user.name "Your Name"

# 设置邮箱(与 GitHub/GitLab 账号一致)
$ git config --global user.email "[email protected]"

# 设置默认编辑器
$ git config --global core.editor "code --wait"  # VS Code
$ git config --global core.editor "vim"           # Vim
$ git config --global core.editor "nano"          # Nano

# 设置默认分支名(推荐 main)
$ git config --global init.defaultBranch main

# 验证配置
$ git config --global --list

2.2.2 推荐配置项

# 设置 pull 策略为 rebase(避免无意义的合并提交)
$ git config --global pull.rebase true

# 自动处理行尾符号
$ git config --global core.autocrlf input    # macOS/Linux
$ git config --global core.autocrlf true     # Windows

# 启用颜色输出
$ git config --global color.ui auto

# 设置 diff 工具
$ git config --global diff.tool vscode
$ git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'

# 设置 merge 工具
$ git config --global merge.tool vscode
$ git config --global mergetool.vscode.cmd 'code --wait $MERGED'

# 忽略文件权限变化
$ git config --global core.fileMode false

# 设置 push 默认行为
$ git config --global push.default current

# 启用自动纠错
$ git config --global help.autocorrect 20

2.2.3 查看和管理配置

# 查看所有配置
$ git config --list

# 查看某个配置项
$ git config user.name
$ git config --global user.email

# 查看配置来源
$ git config --list --show-origin

# 编辑配置文件
$ git config --global -e    # 编辑用户级配置

# 删除配置项
$ git config --global --unset user.name

# 删除整个配置段
$ git config --global --remove-section alias

2.3 SSH Key 配置

SSH (Secure Shell) 是与远程 Git 仓库通信的推荐方式,相比 HTTPS 更安全、更方便。

2.3.1 检查现有 SSH Key

# 查看是否已有 SSH Key
$ ls -la ~/.ssh

# 常见文件
# id_rsa / id_rsa.pub       — RSA 密钥对
# id_ed25519 / id_ed25519.pub — Ed25519 密钥对(推荐)
# known_hosts                 — 已知主机记录
# config                      — SSH 配置文件

2.3.2 生成新的 SSH Key

# 推荐使用 Ed25519 算法(更安全、更短)
$ ssh-keygen -t ed25519 -C "[email protected]"

# 如果系统不支持 Ed25519,使用 RSA
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"

生成过程交互:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/user/.ssh/id_ed25519): [回车使用默认]
Enter passphrase (empty for no passphrase): [输入密码,推荐设置]
Enter same passphrase again: [再次输入密码]
Your identification has been saved in /home/user/.ssh/id_ed25519
Your public key has been saved in /home/user/.ssh/id_ed25519.pub

⚠️ 强烈建议设置 passphrase,即使私钥泄露也能提供额外保护。

2.3.3 启动 SSH Agent

# 启动 ssh-agent
$ eval "$(ssh-agent -s)"
Agent pid 12345

# 添加私钥到 agent
$ ssh-add ~/.ssh/id_ed25519
Enter passphrase for /home/user/.ssh/id_ed25519: [输入密码]

# macOS 特有:将密钥添加到 Keychain
$ ssh-add --apple-use-keychain ~/.ssh/id_ed25519

2.3.4 添加公钥到 GitHub / GitLab

# 复制公钥内容
$ cat ~/.ssh/id_ed25519.pub
# 或使用剪贴板工具
$ xclip -sel clip < ~/.ssh/id_ed25519.pub   # Linux
$ pbcopy < ~/.ssh/id_ed25519.pub            # macOS
$ clip < ~/.ssh/id_ed25519.pub              # Windows

GitHub 添加步骤

  1. 登录 GitHub → Settings → SSH and GPG keys
  2. 点击 “New SSH key”
  3. 粘贴公钥内容
  4. 填写标题(如 “Work Laptop”)
  5. 点击 “Add SSH key”

GitLab 添加步骤

  1. 登录 GitLab → Preferences → SSH Keys
  2. 粘贴公钥内容
  3. 设置过期时间(可选)
  4. 点击 “Add key”

2.3.5 测试连接

# 测试 GitHub 连接
$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not provide shell access.

# 测试 GitLab 连接
$ ssh -T [email protected]
Welcome to GitLab, @username!

2.3.6 SSH 多账户配置

如果你有多个 Git 账号(如个人和工作),需要配置 SSH config:

# 编辑 ~/.ssh/config
$ vim ~/.ssh/config
# 个人 GitHub 账号
Host github.com-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal
    IdentitiesOnly yes

# 工作 GitHub 账号
Host github.com-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work
    IdentitiesOnly yes

# GitLab
Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

克隆时使用对应的 Host:

# 个人仓库
$ git clone [email protected]:username/repo.git

# 工作仓库
$ git clone [email protected]:company/repo.git

设置每个仓库的用户信息:

# 在个人仓库中
$ cd personal-repo
$ git config user.name "Personal Name"
$ git config user.email "[email protected]"

# 在工作仓库中
$ cd work-repo
$ git config user.name "Work Name"
$ git config user.email "[email protected]"

2.4 Git 配置文件详解

完整的 .gitconfig 示例

[user]
    name = Your Name
    email = [email protected]

[init]
    defaultBranch = main

[core]
    editor = code --wait
    autocrlf = input
    fileMode = false
    # 大文件阈值(字节)
    bigFileThreshold = 50m

[pull]
    rebase = true

[push]
    default = current
    autoSetupRemote = true

[fetch]
    prune = true
    prunetags = true

[diff]
    tool = vscode
    algorithm = histogram
    colorMoved = default

[difftool "vscode"]
    cmd = code --wait --diff $LOCAL $REMOTE

[merge]
    tool = vscode
    conflictstyle = diff3

[mergetool "vscode"]
    cmd = code --wait $MERGED

[alias]
    st = status -sb
    co = checkout
    br = branch
    ci = commit
    lg = log --oneline --graph --decorate --all
    last = log -1 HEAD --stat
    unstage = reset HEAD --
    amend = commit --amend --no-edit
    wip = !git add -A && git commit -m "WIP"

[credential]
    helper = cache --timeout=3600

[rerere]
    enabled = true

[help]
    autocorrect = 20

[url "[email protected]:"]
    insteadOf = https://github.com/

仓库级配置 .git/config

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
    remote = origin
    merge = refs/heads/main

2.5 验证安装和配置

完整验证清单

# 1. 检查 Git 版本
$ git --version
git version 2.45.0

# 2. 检查配置
$ git config --list --show-origin

# 3. 检查用户信息
$ git config user.name && git config user.email

# 4. 测试创建仓库
$ mkdir test-repo && cd test-repo
$ git init
Initialized empty Git repository in /tmp/test-repo/.git/

# 5. 测试提交
$ echo "# Test" > README.md
$ git add README.md
$ git commit -m "Initial commit"
[main (root-commit) abc1234] Initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 README.md

# 6. 检查日志
$ git log --oneline
abc1234 Initial commit

# 7. 清理测试仓库
$ cd .. && rm -rf test-repo

2.6 常见问题排查

问题原因解决方案
git: command not found未安装或未加入 PATH重新安装或添加 PATH
Permission denied (publickey)SSH Key 未配置添加公钥到远程平台
Author identity unknown未设置 user.name/emailgit config --global 设置
warning: LF will be replaced by CRLF行尾符号问题设置 core.autocrlf
fatal: not a git repository不在 Git 仓库目录cd 到正确目录或 git init

业务场景

场景推荐配置
个人开发全局 user.name/email + SSH Key
团队协作仓库级用户信息 + 统一 .gitconfig 模板
多项目多身份SSH config 多账户 + conditional includes
CI/CD 环境Deploy Key + git config 环境变量
Windows 团队统一 core.autocrlf = true

Conditional Includes(Git 2.36+)

按目录自动切换配置:

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

扩展阅读


🔗 上一章01 - 简介 | 下一章03 - 基础操作