Git 基础安装与配置完全指南(3000+字详解 + 图表辅助)
1. 引言
Git 是目前最流行的分布式版本控制系统,广泛应用于软件开发、DevOps、数据分析等领域。无论是个人项目还是团队协作,Git 都能高效管理代码变更。
然而,许多初学者在安装和配置 Git 时遇到各种问题,比如:
- Git 命令无法识别(环境变量未配置)
- 提交记录没有正确的作者信息(未设置
user.name
和user.email
) - 换行符冲突(Windows/macOS/Linux 换行符差异导致代码混乱)
本文将从 Git 安装、基本配置、测试验证、常见问题解决 四个方面,详细介绍如何在 Windows、macOS 和 Linux 上正确安装 Git,并确保其正常运行。
2. 不同操作系统下的 Git 安装
2.1 Windows 系统安装 Git
方法 1:官方安装包(推荐)
-
下载 Git for Windows
- 访问 git-scm.com 下载最新版(如
Git-2.45.0-64-bit.exe
)。
- 访问 git-scm.com 下载最新版(如
-
运行安装程序
-
选择组件(默认全选):
Git Bash
(Linux 风格命令行)Git GUI
(图形界面)Git LFS
(大文件支持)
(图2:Git 安装组件选择界面)
-
调整 PATH 环境变量(建议选
Git from the command line and also from 3rd-party software
,以便全局使用git
命令)。
(图3:Git 的 PATH 环境变量配置)
-
✅ 验证安装:
git --version # 应显示类似 git version 2.45.0
2.2 macOS 系统安装 Git
方法 1:使用 Homebrew(推荐)
-
安装 Homebrew(如未安装)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
-
用 Homebrew 安装 Git
brew install git
✅ 验证安装:
git --version
2.3 Linux 系统安装 Git
不同 Linux 发行版安装方式不同:
发行版 | 安装命令 |
---|---|
Debian/Ubuntu | sudo apt install git |
RHEL/CentOS | sudo yum install git |
Arch Linux | sudo pacman -S git |
✅ 验证安装:
git --version
3. Git 初始配置(首次使用必做)
3.1 设置全局用户信息
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
📌 说明:
--global
表示全局配置(适用于所有仓库)。- 公司项目可能需要单独设置(去掉
--global
)。
3.2 检查当前配置
git config --list
输出示例:
user.name=Your Name
user.email=your.email@example.com
core.editor=code --wait
core.autocrlf=true
3.3 换行符处理(跨平台协作关键)
操作系统 | 推荐设置 | 命令 |
---|---|---|
Windows | core.autocrlf=true | git config --global core.autocrlf true |
Linux/macOS | core.autocrlf=input | git config --global core.autocrlf input |
4. 测试 Git 是否正常工作
4.1 创建测试仓库
mkdir test-repo && cd test-repo
git init
echo "# Test Git" > README.md
git add README.md
git commit -m "Initial commit"
4.2 查看提交记录
git log
输出示例:
commit abc123...
Author: Your Name <your.email@example.com>
Date: Mon Jun 30 12:00:00 2024 +0800
Initial commit
5. 常见问题及解决方案
问题排查流程图
(图5:Git 常见问题排查流程)
6. 总结
本文通过 图文结合 的方式详细讲解了:
✅ 多平台 Git 安装方法
✅ 关键配置项(用户名、换行符处理)
✅ 测试验证流程
✅ 问题排查技巧
下一步建议:
- 练习基本 Git 命令(
clone
,branch
,merge
) - 注册 GitHub 并创建第一个仓库
- 学习
.gitignore
文件的使用
📚 扩展阅读:
通过本指南,你已掌握 Git 的安装与核心配置,现在可以开始你的版本控制之旅了!🚀