【Git】从入门到精通(二)—— Git安装与初次配置

作者:全栈陈序员 系列:《Git版本控制从入门到精通》 适用人群:零基础到入门进阶 阅读时间:约 18 分钟


大家好

上一篇我们搞懂了"什么是版本控制""Git 为什么这么设计"。从本篇开始,我们要真正动手了。

工欲善其事,必先利其器。本篇会带你:

  • 在 Windows / macOS / Linux 三大平台安装 Git;
  • 理解 Git 的三个配置级别(system / global / local);
  • 完成初次必须的配置(用户名、邮箱);
  • 配置编辑器、SSH 密钥、命令别名、颜色、换行符;
  • 学会使用 git help 查阅帮助。

完成后,你的 Git 环境就"整装待发"了。


一、各平台安装 Git

1.1 Windows 安装

Windows 系统本身不自带 Git,需要手动安装。推荐使用 Git for Windows ,它是一个完整的 Git 移植版本,自带一个模拟 Linux 命令行的 Git Bash,对新手非常友好。

安装步骤:

  1. 访问官网下载页:https://git-scm.com/download/win,会自动开始下载最新版安装包(如 Git-2.45.0-64-bit.exe)。
  2. 双击运行安装包,关键选项说明:
    • Select Components:勾选 "Git Bash Here" 和 "Git GUI Here",方便右键菜单快速打开;
    • Adjusting your PATH environment :选择 "Git from the command line and also from 3rd-party software" (推荐),这样在 CMD / PowerShell 里也能用 git 命令;
    • Choosing the default editor:根据喜好选择 Vim / Nano / VS Code;
    • Default branch name :建议填 main(2020年后新约定,后面会讲)。
  3. 一路 Next,完成安装。

安装完成后,在桌面右键 → "Git Bash Here",打开终端:

复制代码
$ git --version
git version 2.45.0.windows.1

看到版本号即安装成功。

关于 Git Bash :Git Bash 是 Git for Windows 自带的类 Unix 终端,提供 ls、cd、grep、ssh 等命令。对于习惯了 Linux 命令的开发者,在 Windows 上用 Git Bash 比用 CMD/PowerShell 体验好很多。本系列所有命令示例默认在 Git Bash 或类 Unix 终端下运行。

1.2 macOS 安装

macOS 安装 Git 有三种常见方式:

方式一:Homebrew(推荐)

如果你装了 Homebrew(macOS 的包管理器),一行命令搞定:

复制代码
$ brew install git

安装完成后验证:

复制代码
$ git --version
git version 2.45.0

方式二:Xcode Command Line Tools

即使不装完整的 Xcode,也可以装"命令行工具",它会附带 Git:

复制代码
$ xcode-select --install

弹出对话框后点"安装",等待完成。这种方式装的 Git 版本可能略旧,但够用。

方式三:官方安装包

访问 https://git-scm.com/download/mac,下载 .dmg 安装包,双击安装。

提示 :macOS 自带的 git 可能是 Apple 维护的版本,功能上没问题,但版本可能落后于官方。追求新版本建议用 Homebrew。

1.3 Linux 安装

不同发行版用不同包管理器:

Debian / Ubuntu:

复制代码
$ sudo apt update
$ sudo apt install git

CentOS / RHEL / Fedora:

复制代码
# 旧版 CentOS
$ sudo yum install git

# Fedora / 新版 RHEL
$ sudo dnf install git

Arch Linux:

复制代码
$ sudo pacman -S git

openSUSE:

复制代码
$ sudo zypper install git

源码编译安装(获取最新版):

有时发行版仓库里的 Git 版本较旧,需要源码编译:

复制代码
# 安装依赖
$ sudo apt install build-essential libssl-dev libcurl4-gnutls-dev libexpat1-dev gettext zlib1g-dev

# 下载源码
$ wget https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.45.0.tar.gz
$ tar -zxf git-2.45.0.tar.gz
$ cd git-2.45.0

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

1.4 验证安装

无论哪个平台,安装后都执行:

复制代码
$ git --version
git version 2.45.0

看到版本号即说明 Git 已成功安装到 PATH 中。

如果提示 command not found,说明 Git 没有加入环境变量,需要手动把 Git 的 bin 目录加入 PATH。


二、Git的三个配置级别

Git 的配置信息存储在三个不同级别的文件中,理解它们的优先级非常重要。

2.1 system 级(系统级)

  • 文件位置 :/etc/gitconfig(Windows 在 C:\Program Files\Git\etc\gitconfig)

  • 作用范围 :系统上所有用户的所有仓库

  • 配置命令 :git config --system <key> <value>

  • 使用场景:极少使用,通常由系统管理员统一设置

    查看系统级配置

    $ git config --system --list

2.2 global 级(全局级/用户级)

  • 文件位置 :~/.gitconfig(即 /home/用户名/.gitconfig,Windows 在 C:\Users\用户名\.gitconfig)

  • 作用范围 :当前用户的所有仓库

  • 配置命令 :git config --global <key> <value>

  • 使用场景:最常用!设置用户名、邮箱、别名等个人偏好

    查看全局配置

    $ git config --global --list

2.3 local 级(仓库级)

  • 文件位置 :<仓库目录>/.git/config

  • 作用范围 :仅当前仓库

  • 配置命令 :git config --local <key> <value>(--local 可省略,默认就是 local)

  • 使用场景:某个仓库需要特殊配置,比如公司项目用公司邮箱、个人项目用私人邮箱

    查看当前仓库配置

    $ git config --local --list

2.4 优先级

当同一配置项在多个级别都存在时,Git 按就近原则取值:

复制代码
local(仓库级) > global(用户级) > system(系统级)

即:仓库级配置会覆盖全局级,全局级覆盖系统级。

典型应用 :你全局配置的是私人邮箱,但公司项目要用公司邮箱提交,就在公司仓库里用 --local 单独配置:

复制代码
# 在公司项目仓库目录下
$ git config user.name "陈公司"
$ git config user.email "chen@company.com"

这样这个仓库提交时用公司身份,其他仓库仍用全局的私人身份。


三、初次必须配置

安装完 Git,第一件事 就是配置用户名和邮箱。这不是可选项,而是必须项。

3.1 配置用户名和邮箱

复制代码
# 配置全局用户名
$ git config --global user.name "全栈陈序员"

# 配置全局邮箱
$ git config --global user.email "chensen@example.com"

3.2 为什么必须配置

Git 的每一次提交都会永久记录提交者的用户名和邮箱,写入提交对象,不可更改(除非重写历史):

复制代码
commit 3e92b4a8e5f1c2d9b7a3f6e8d4c2b1a9f0e7d6c5
Author: 全栈陈序员 <chensen@example.com>
Date:   Mon Nov 2 10:00:00 2026 +0800

    初始提交

如果没配置,首次 git commit 时 Git 会报错:

复制代码
$ git commit -m "初始提交"

Author identity not known yet.

Please tell me who you are.

Run

  git config --global user.name "Your Name"
  git config --global user.email "you@example.com"

to set your account's identity in this repository.

If you want to set identity only for this repository, omit --global.

Aborting commit; no identity configured.

Git 会拒绝提交,直到你配置好身份。

重要 :如果你打算把代码推送到 GitHub/GitLab,邮箱要和平台账号绑定的邮箱一致,这样平台才能把提交正确关联到你的账号,显示在你的贡献图(绿格子)上。

3.3 查看配置

查看所有配置(合并三个级别):

复制代码
$ git config --list
user.name=全栈陈序员
user.email=chensen@example.com
core.editor=vim
core.autocrlf=input
color.ui=auto

查看某一项配置:

复制代码
$ git config user.name
全栈陈序员

$ git config user.email
chensen@example.com

查看配置来自哪个文件:

复制代码
$ git config --list --show-origin
file:/home/chensen/.gitconfig     user.name=全栈陈序员
file:/home/chensen/.gitconfig     user.email=chensen@example.com

--show-origin 会显示每个配置项来自哪个文件,排查配置冲突时非常有用。

3.4 直接编辑配置文件

你也可以直接用编辑器打开配置文件修改:

复制代码
# 编辑全局配置
$ git config --global --edit

# 或者直接用 vim/nano
$ vim ~/.gitconfig

配置文件是 INI 格式,例如:

复制代码
[user]
    name = 全栈陈序员
    email = chensen@example.com
[core]
    editor = vim
    autocrlf = input
[color]
    ui = auto

四、配置编辑器和diff工具

4.1 配置默认编辑器

Git 在某些场景会调用编辑器让你输入文本,比如:git commit 不带 -m 时会让你写提交信息,git config --edit 时让你编辑配置。

复制代码
# 使用 vim
$ git config --global core.editor vim

# 使用 nano(对新手更友好)
$ git config --global core.editor nano

# 使用 VS Code(需要 code 命令在 PATH 中)
$ git config --global core.editor "code --wait"

# 使用 Sublime Text
$ git config --global core.editor "subl -n -w"

--wait 参数很关键:它让 Git 等待编辑器关闭后再继续。否则 Git 会立即读到空内容。

4.2 配置 diff 工具

默认的 git diff 是终端文本输出,也可以配置可视化 diff 工具:

复制代码
# 配置 vimdiff 作为 diff 工具
$ git config --global diff.tool vimdiff

# 配置 VS Code 作为 diff 工具
$ git config --global diff.tool vscode
$ git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'

# 启动 difftool
$ git difftool

类似地可以配置 merge.tool 用于解决合并冲突:

复制代码
$ git config --global merge.tool vscode
$ git config --global mergetool.vscode.cmd 'code --wait $MERGED'

五、配置SSH密钥

推送代码到 GitHub/GitLab 时,有两种认证方式:HTTPS 和 SSH。SSH 方式不用每次输密码,更安全更方便,是推荐做法。

5.1 检查是否已有SSH密钥

复制代码
$ ls -al ~/.ssh

如果已有 id_ed25519(私钥)和 id_ed25519.pub(公钥),可以跳过生成步骤。

5.2 生成新的SSH密钥

推荐使用更安全的 ed25519 算法:

复制代码
$ ssh-keygen -t ed25519 -C "chensen@example.com"

终端会提示:

复制代码
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/chensen/.ssh/id_ed25519):   # 直接回车用默认路径
Enter passphrase (empty for no passphrase):                            # 可以设密码,也可留空
Enter same passphrase again:                                           # 重复密码

完成后会输出:

复制代码
Your identification has been saved in /home/chensen/.ssh/id_ed25519
Your public key has been saved in /home/chensen/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx chensen@example.com
The key's randomart image is:
+--[ED25519 256]----+
|        . . o .   |
|         o = o .  |
|        . o + .   |
|       . . = .    |
|        S . =     |
|       . . = .    |
|      . o . o     |
|     . o . .      |
|      . .         |
+----[SHA256]-----+

老系统不支持 ed25519 时,退而求其次用 RSA:ssh-keygen -t rsa -b 4096 -C "邮箱"

5.3 启动ssh-agent并添加私钥

复制代码
# 启动 ssh-agent
$ eval "$(ssh-agent -s)"
Agent pid 12345

# 添加私钥
$ ssh-add ~/.ssh/id_ed25519
Identity added: /home/chensen/.ssh/id_ed25519 (chensen@example.com)

macOS 从 10.12.2 起建议把密钥配置到 keychain:ssh-add --apple-use-keychain ~/.ssh/id_ed25519

5.4 复制公钥并添加到GitHub

复制公钥到剪贴板:

复制代码
# macOS
$ pbcopy < ~/.ssh/id_ed25519.pub

# Linux (需要 xclip)
$ xclip -selection clipboard < ~/.ssh/id_ed25519.pub

# Windows (Git Bash)
$ clip < ~/.ssh/id_ed25519.pub

# 通用:直接 cat 查看,手动复制
$ cat ~/.ssh/id_ed25519.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... chensen@example.com

添加到 GitHub:

  1. 登录 GitHub → 右上角头像 → Settings → SSH and GPG keys → New SSH key;
  2. Title 填一个便于识别的名字(如 "MacBook Pro");
  3. Key 粘贴刚才复制的公钥内容;
  4. 点 "Add SSH key"。

5.5 测试SSH连接

复制代码
$ ssh -T git@github.com
The authenticity of host 'github.com' (140.82.114.3) can't be established.
ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJh5Zm1n+...
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes   # 首次连接输入 yes
Warning: Permanently added 'github.com' (ED25519) to the list of known hosts.
Hi chensen! You've successfully authenticated, but GitHub does not provide shell access.

看到 Hi 用户名! You've successfully authenticated 即配置成功。

GitLab / Gitee 的测试命令分别是 ssh -T git@gitlab.com 和 ssh -T git@gitee.com。


六、配置命令别名

Git 命令有些比较长,频繁敲很累。Git 支持给命令起别名,大幅提升效率。

6.1 设置别名

复制代码
# 基础别名
$ git config --global alias.st status          # git st = git status
$ git config --global alias.co checkout        # git co = git checkout
$ git config --global alias.ci commit          # git ci = git commit
$ git config --global alias.br branch          # git br = git branch
$ git config --global alias.sw switch          # git sw = git switch
$ git config --global alias.unstage 'reset HEAD --'  # git unstage <file> = 取消暂存

# 查看历史的美化别名(超实用)
$ git config --global alias.lg "log --color --graph --pretty=format:'%C(bold yellow)%h%C(reset) - %C(bold green)(%ar)%C(reset) %s %C(bold red)(%an)%C(reset)' --abbrev-commit"

使用示例:

复制代码
$ git st
On branch main
nothing to commit, working tree clean

$ git lg
* d3f1a2b - (2 hours ago) 添加登录功能 (全栈陈序员)
* 3e92b4a - (5 hours ago) 初始提交 (全栈陈序员)

6.2 推荐的别名集

复制代码
$ git config --global alias.last 'log -1 HEAD'           # 查看最近一次提交
$ git config --global alias.aliases '!git config -l | grep alias'  # 查看所有别名
$ git config --global alias.amend 'commit --amend --no-edit'      # 追加到上次提交不改信息
$ git config --global alias.undo 'reset --soft HEAD~1'            # 撤销最近一次提交但保留改动
$ git config --global alias.wip 'commit -m "WIP"'                 # 快速存一个工作进度

以 ! 开头的别名表示执行外部 Shell 命令,而非 Git 子命令。

6.3 查看已配置的别名

复制代码
$ git config --get-regexp alias
alias.st status
alias.co checkout
alias.ci commit
alias.br branch
alias.lg log --color --graph --pretty=format:...

七、配置颜色和换行符

7.1 颜色输出

Git 默认会自动启用颜色,但可以显式配置:

复制代码
$ git config --global color.ui auto

可选值:

  • auto:终端支持就着色,不支持就不着色(推荐);
  • always:总是着色(管道重定向时也着色,可能干扰其他工具);
  • never:从不着色。

效果:git status、git log、git diff 的输出会有不同颜色区分,可读性大增。

7.2 换行符问题(Windows vs Mac/Linux)

这是一个经典跨平台坑:

  • Windows :换行符是 CRLF(\r\n),回车+换行两个字符;
  • macOS / Linux :换行符是 LF(\n),只有换行一个字符。

当 Windows 用户和 Mac 用户协作同一个仓库时,如果不处理,会出现:同一文件被不同人改了换行符,git diff 显示整个文件都变了,合并冲突频发。

Git 提供 core.autocrlf 配置来处理:

Windows 用户推荐:

复制代码
$ git config --global core.autocrlf true

含义:提交时把 CRLF 转成 LF,检出时把 LF 转成 CRLF。仓库里统一存 LF,本地工作区用 CRLF。

macOS / Linux 用户推荐:

复制代码
$ git config --global core.autocrlf input

含义:提交时把 CRLF 转成 LF,检出时不转换。仓库里统一存 LF,本地也用 LF。

关闭自动转换(不推荐,除非你明确知道后果):

复制代码
$ git config --global core.autocrlf false

更现代的做法 :在仓库根目录创建 .gitattributes 文件强制指定:

复制代码
* text=auto
*.sh  text eol=lf
*.bat text eol=crlf
*.png binary

这种方式比全局配置更可靠,且对全团队生效,后面会专门讲。


八、Git帮助命令

Git 命令众多,没人能全记住。学会查帮助比死记硬背重要得多。

8.1 三种查帮助的方式

复制代码
# 方式一:git help <命令>
$ git help config       # 在浏览器或 man 中打开 git config 的完整文档

# 方式二:git <命令> --help
$ git config --help     # 同上

# 方式三:man git-<命令>
$ man git-config        # Unix 系统的 man 手册

三者基本等价,都会打开详细的命令文档。

8.2 快速概览(不带参数)

复制代码
# 查看 git 所有顶层命令的概要
$ git --help
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<namespace>]
           <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone     Clone a repository into a new directory
   init      Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
   add       Add file contents to the index
   mv        Move or rename a file, a directory, or a symlink
   restore   Restore working tree files
   rm        Remove files from the working tree and from the index

examine the history and state (see also: git help revisions)
   bisect    Use binary search to find the commit that introduced a bug
   diff      Show changes between commits, commit and working tree, etc
   grep      Print lines matching a pattern
   log       Show commit logs
   show      Show various types of objects
   status    Show working tree status
...

8.3 查看某命令的快速用法

复制代码
$ git config -h
usage: git config [<options>]

Config file location
    --global              use global config file
    --system              use system config file
    --local               use repository config file
    --worktree            use per-worktree config file
...

-h(短帮助)只输出用法摘要,比完整文档精简,适合快速查阅。


九、常见安装问题FAQ

Q1:Windows 安装后,在 CMD 里输入 git 提示"不是内部或外部命令"?

A:安装时没勾选"将 Git 加入 PATH"。重新安装,选择 "Git from the command line and also from 3rd-party software";或手动把 C:\Program Files\Git\cmd 加入系统 PATH。

Q2:macOS 上 git --version 显示 apple-github 或版本很老?

A:这是 Xcode Command Line Tools 附带的 Apple 维护版。要装官方最新版:brew install git,然后确认 which git 指向 /opt/homebrew/bin/git(M系列芯片)或 /usr/local/bin/git(Intel芯片)。

Q3:git config --global 后,配置文件在哪?

A:在 ~/.gitconfig。Windows 是 C:\Users\你的用户名\.gitconfig。可以直接用编辑器打开查看。

Q4:SSH 连接 GitHub 超时?

A:可能是网络问题。尝试:

复制代码
# 测试连通性
$ ssh -vT git@github.com

# 如果 22 端口被墙,改用 443 端口
# 在 ~/.ssh/config 添加:
Host github.com
    Hostname ssh.github.com
    Port 443

Q5:公司用代理上网,Git 怎么配置代理?

A:

复制代码
# HTTP 代理
$ git config --global http.proxy http://proxy.company.com:8080
$ git config --global https.proxy http://proxy.company.com:8080

# 取消代理
$ git config --global --unset http.proxy
$ git config --global --unset https.proxy

# 只对某个域名走代理
$ git config --global http.https://github.com.proxy http://proxy.company.com:8080

Q6:能否配置默认的初始分支名为 main?

A:可以,Git 2.28+ 支持:

复制代码
$ git config --global init.defaultBranch main

这样以后 git init 默认创建的分支就叫 main 而非 master。

Q7:配置写错了怎么删除?

A:

复制代码
# 删除某一项
$ git config --global --unset user.name

# 删除整个小节
$ git config --global --remove-section alias

十、小结

本篇我们完成了 Git 环境的搭建与初始化:

  1. 安装 :Windows 用 Git for Windows,macOS 用 Homebrew,Linux 用包管理器或源码编译,安装后用 git --version 验证。
  2. 三个配置级别:system(系统)< global(用户)< local(仓库),优先级 local 最高。
  3. 必须配置 :user.name 和 user.email,因为每次提交都会永久记录。可用 git config --list 查看。
  4. 编辑器与 diff 工具 :core.editor、diff.tool、merge.tool。
  5. SSH 密钥 :ssh-keygen 生成,公钥添加到 GitHub,ssh -T git@github.com 测试。
  6. 命令别名 :git config --global alias.xx yy,大幅提升效率,推荐一套常用别名。
  7. 颜色与换行符 :color.ui auto;Windows 设 core.autocrlf true,Mac/Linux 设 input,或用 .gitattributes 强制管理。
  8. 帮助命令 :git help <cmd>、git <cmd> --help、git <cmd> -h,学会查帮助比背命令重要。

至此,你的 Git 环境已经完全就绪。下一篇,我们将创建第一个 Git 仓库,跑通"初始化 → 添加 → 提交 → 查看历史"的完整流程,亲手感受 Git 的魅力。

下一篇:《Git从入门到精通(三)------ 创建第一个Git仓库》


如果本文对你有帮助,欢迎点赞、收藏、关注。我是全栈陈序员,我们下篇见。

相关推荐
XLYcmy2 小时前
实验报告分析评价文档——《第四次阶段汇报:模型产物的仓库瘦身、云端部署与评测链路打通》评析
git·llm·cpu·gpu·反编译·反汇编·safetensors
全栈陈序员2 小时前
【Git】从入门到精通(三)—— 创建第一个Git仓库
大数据·git·elasticsearch
程序员梅雨2 小时前
【从零开始学习数据仓库 | 第三篇】: Flume——数据采集基石
java·大数据·数据仓库·后端·学习·flume
全栈陈序员2 小时前
【Git】从入门到精通(四)—— Git三大区域:工作区、暂存区与版本库
大数据·git·elasticsearch
YIN_尹2 小时前
【git原理与使用】git基本操作及底层原理(一)
java·git·elasticsearch
AI 编程助手GPT3 小时前
GPT 改完配置别直接覆盖:用 git diff 审查两份文件
git·gpt
叼烟扛炮14 小时前
[Git 实战] 学习笔记:从生成 SSH 密钥到解决 TortoiseGit 推送报错全指南
linux·运维·笔记·git·学习
netyeaxi20 小时前
Git:git深入理解及常见问题
git
蹊黎1 天前
Git 从入门到精通(二):创建本地仓库与三大核心区域
git