Git 完全教程
从零开始理解 Git:它是什么、为什么需要它、核心概念、常用命令与实战工作流
一、什么是 Git
Git 是一个分布式版本控制系统(Distributed Version Control System),由 Linus Torvalds 于 2005 年创建,最初用于管理 Linux 内核的源代码。
关键特性
分布式:每个人的本地电脑都拥有完整的仓库副本(包括所有历史记录),不依赖中央服务器即可工作。
快照式存储:Git 不是记录文件的差异,而是每次提交都保存完整的文件快照。未变更的文件会以指针引用之前的版本,既高效又可靠。
几乎所有的操作都在本地执行:查看日志、创建分支、提交代码等操作无需网络连接,速度极快。
数据完整性保障:每个文件的内容都通过 SHA-1 哈希值校验,任何篡改都会被立刻发现。
二、为什么需要 Git
没有 Git 的世界
假设没有版本控制,开发者通常的做法是手动复制文件夹并重命名:project_v1、project_v2、project_final、project_final_v2…… 这种方式存在严重问题:
- 无法追溯每个版本具体改了什么
- 多人协作时容易覆盖彼此的代码
- 误删文件后无法恢复
- 文件名混乱、版本关系不清晰
- 浪费大量磁盘空间(每次都是完整复制)
Git 解决的核心问题
版本追踪
完整记录每次改动的谁、什么时间、改了什么内容,随时查看差异对比。
多人协作
分支(Branch)机制让多人可以并行开发不同功能,最终合并到一起。
随时回退
发现严重 Bug 可以一键回退到之前的稳定版本,不用担心误操作。
代码备份
推送到远程仓库(GitHub/GitLab)后,即使本地电脑损坏,代码也不会丢失。
三、核心概念
3.1 Git 的四个区域
Working Dir →
git add →
暂存区Staging Area →
git commit →
本地仓库Local Repo →
git push →
远程仓库Remote Repo
工作区 = 电脑上看到的文件;暂存区 = 准备提交的改动清单;本地仓库 = 本地的版本数据库;远程仓库 = GitHub/GitLab 上的服务器端仓库。
3.2 仓库(Repository / Repo)
仓库是 Git 管理的基本单元。一个仓库对应一个项目,包含该项目的所有文件、版本历史、分支等信息。通过 git init 或 git clone 创建。
3.3 提交(Commit)
提交是 Git 中最基本的操作单元。每次 git commit 都会创建一个新的快照(Snapshot),记录当前暂存区中所有文件的状态。每个提交有唯一的 SHA-1 哈希 ID(如 a1b2c3d)。
3.4 分支(Branch)
分支是代码的独立发展线。默认分支是 main(旧版本叫 master)。可以在分支上开发新功能、修复 Bug,完成后合并回主分支,互不影响。
3.5 HEAD
HEAD 是一个特殊指针,指向当前工作所在的最新提交。切换分支时,HEAD 会移动到目标分支的最新提交。
3.6 标签(Tag)
标签是对某个提交的固定命名引用,通常用于标记版本发布,如 v1.0.0、v2.1.3。
四、安装与初始配置
4.1 安装 Git
macOS
Linux (Debian/Ubuntu)
4.2 初始配置
# 设置用户名(会显示在提交记录中) git config --global user.name "Your Name" # 设置邮箱(建议与 GitHub/GitLab 注册邮箱一致) git config --global user.email "you@example.com" # 设置默认分支名为 main(新版 Git 已默认) git config --global init.defaultBranch main # 查看当前配置 git config --list # 查看某个配置项 git config user.name
--global 表示全局配置(对所有仓库生效)。如果只想对某个仓库单独设置,去掉 --global 在仓库目录下执行即可。
五、基础命令:创建与提交
5.1 创建仓库
方式 A:git init 从零创建
# 进入项目文件夹 cd /path/to/project # 初始化为 Git 仓库(创建 .git 隐藏文件夹) git init # 查看仓库状态 git status
方式 B:git clone 克隆已有仓库
# HTTPS git clone https://github.com/user/repo.git # SSH git clone git@github.com:user/repo.git # 克隆到指定文件夹名 git clone https://... my-project
5.2 文件状态生命周期
未追踪 →
git add
Staged已暂存 →
git commit
Committed已提交
git status
git add
git commit
git diff
5.3 .gitignore 文件
.gitignore 文件指定哪些文件/目录不纳入 Git 管理(如编译产物、系统文件、敏感信息):
# 编译产物 node_modules/ __pycache__/ *.pyc build/ dist/ # 系统文件 .DS_Store Thumbs.db # 环境配置(包含敏感信息) .env .env.local # IDE 配置 .vscode/ .idea/
六、分支管理
分支是 Git 最强大的功能之一——它允许并行开发不同功能,互不干扰。
git branch
git checkout / switch
git switch 是新版推荐命令git merge
git branch -d
feature/(新功能)、bugfix/ 或 fix/(修复)、hotfix/(紧急修复)、docs/(文档)、refactor/(重构)。
七、远程仓库协作
7.1 关联远程仓库
# 查看远程仓库 git remote -v # 添加远程仓库(通常在 git clone 时自动完成) git remote add origin https://github.com/user/repo.git # 修改远程仓库地址 git remote set-url origin https://new-url/repo.git
7.2 推送与拉取
git push
git pull
git fetch
git clone
push = 本地→远程;pull = 远程→本地(自动合并);fetch = 远程→本地(仅下载不合并)。建议每次开发前先 git pull,减少冲突。
八、查看历史与回退
git log
git show
git reset
git revert
reset --hard 会改写历史并永久丢失代码,仅适用于未推送的本地提交。revert 会创建新的提交来撤销,不改写历史,适合已推送的公共分支。
九、暂存与清理
git stash
git stash pop / apply
git clean
git stash 暂存当前改动 → git checkout main → 修 Bug → git checkout feature → git stash pop 恢复继续开发。
十、合并与冲突解决
10.1 合并方式
git merge(合并提交)
git rebase(变基)
10.2 冲突解决流程
当两个分支修改了同一文件的同一位置时,Git 无法自动合并,产生冲突(CONFLICT)。
- Git 会标记冲突文件 git status 冲突文件显示为 “both modified”
-
打开冲突文件,搜索冲突标记
<<<<<<< HEAD(当前分支改动)和=======(分隔线)和>>>>>>> incoming(另一分支改动) - 手动编辑保留正确内容,删除所有冲突标记 VS Code 等编辑器提供可视化冲突解决界面(Accept Current / Incoming / Both)
- 标记冲突已解决并提交 git add . git commit -m “resolve merge conflict in config.py”
十一、高级技巧
git cherry-pick
git tag
git bisect
git blame
十二、推荐工作流
12.1 个人项目
12.2 团队协作(Feature Branch Workflow)
- 从 main 创建功能分支 git checkout main git pull git checkout -b feature/user-auth
- 在功能分支上开发和提交 git add . git commit -m “feat: add user authentication” 可以多次 commit
- 推送功能分支到远程 git push -u origin feature/user-auth
- 在 GitHub/GitLab 上创建 Pull Request (PR) 团队成员 Code Review 通过后合并
- 合并后删除功能分支 git checkout main git pull git branch -d feature/user-auth
12.3 常用命令速查表
| 场景 | 命令 |
|---|---|
| 初始化仓库 | git init |
| 克隆仓库 | git clone <url> |
| 查看状态 | git status |
| 添加到暂存区 | git add . |
| 提交 | git commit -m "message" |
| 推送到远程 | git push |
| 拉取远程更新 | git pull |
| 创建分支 | git checkout -b <branch> |
| 切换分支 | git checkout <branch> |
| 合并分支 | git merge <branch> |
| 查看日志 | git log --oneline |
| 撤销上次提交(保留改动) | git reset --soft HEAD~1 |
| 撤销某次提交(安全) | git revert <hash> |
| 暂存当前改动 | git stash |
| 恢复暂存 | git stash pop |
Complete Git Guide
Learn Git from scratch: what it is, why you need it, core concepts, commands, and practical workflows
Table of Contents
1. What is Git
Git is a Distributed Version Control System (DVCS), created by Linus Torvalds in 2005, originally to manage the Linux kernel source code.
Key Characteristics
Distributed: Every developer’s local machine has a complete copy of the repository (including all history). No central server is required for most operations.
Snapshot-based: Git doesn’t store file diffs — each commit saves a full snapshot. Unchanged files are referenced by pointers to previous versions, making it both efficient and reliable.
Local operations: Viewing logs, creating branches, committing code — all work offline without network access, making it extremely fast.
Data integrity: Every file is checksummed with SHA-1 hashes. Any corruption or tampering is immediately detected.
2. Why Git
Life Without Git
Without version control, developers resort to manually copying and renaming folders: project_v1, project_v2, project_final, project_final_v2… This approach has serious problems:
- No way to trace what changed between versions
- Team members easily overwrite each other’s code
- Deleted files cannot be recovered
- Confusing file names with unclear version relationships
- Massive disk waste (each copy is a full duplicate)
What Git Solves
Version Tracking
Records who changed what, when, and why for every modification. View diffs at any time.
Team Collaboration
Branches let multiple people work in parallel on different features, then merge seamlessly.
Easy Rollback
Found a critical bug? Revert to any stable version instantly. No more fear of mistakes.
Code Backup
Push to GitHub/GitLab and your code is safe — even if your computer dies, nothing is lost.
3. Core Concepts
3.1 The Four Areas
git add →
Staging Area
→ git commit →
Local Repo
→ git push →
Remote Repo
Working Dir = files on your computer; Staging Area = a checklist of changes ready to commit; Local Repo = your local version database; Remote Repo = the server-side repository on GitHub/GitLab.
3.2 Repository (Repo)
A repository is the basic unit managed by Git. One repo = one project, containing all files, version history, branches, etc. Created via git init or git clone.
3.3 Commit
A commit is the fundamental unit of work in Git. Each git commit creates a new snapshot of all staged files. Every commit has a unique SHA-1 hash ID (e.g. a1b2c3d).
3.4 Branch
A branch is an independent line of development. The default branch is main (older versions used master). Develop features or fix bugs on branches, then merge back — no interference.
3.5 HEAD
HEAD is a special pointer to the latest commit of your current branch. Switching branches moves HEAD to the target branch’s latest commit.
3.6 Tag
A tag is a named reference to a specific commit, typically used for version releases like v1.0.0, v2.1.3.
4. Installation & Setup
4.1 Install Git
macOS
Linux (Debian/Ubuntu)
4.2 Initial Configuration
# Set username (shown in commit history) git config --global user.name "Your Name" # Set email (should match your GitHub/GitLab registration) git config --global user.email "you@example.com" # Set default branch name to main git config --global init.defaultBranch main # View current config git config --list # View a specific config value git config user.name
--global applies to all repos. Omit it to set per-repo configuration.
5. Basics: Create & Commit
5.1 Create a Repository
Method A: git init From Scratch
cd /path/to/project git init git status
Method B: git clone Clone Existing
# HTTPS git clone https://github.com/user/repo.git # SSH git clone git@github.com:user/repo.git # Clone to custom folder name git clone https://... my-project
5.2 File Lifecycle
git add
Staged
→ git commit
Committed
git status
git add
git commit
git diff
5.3 .gitignore
Specifies files/directories to exclude from Git tracking:
# Build artifacts node_modules/ __pycache__/ *.pyc build/ dist/ # OS files .DS_Store Thumbs.db # Environment configs (may contain secrets) .env .env.local # IDE configs .vscode/ .idea/
6. Branch Management
Branches are one of Git’s most powerful features — enabling parallel development without interference.
git branch
git checkout / switch
git switch is the modern recommended command.git merge
git branch -d
feature/, bugfix/ or fix/, hotfix/, docs/, refactor/.
7. Remote Repositories
7.1 Link Remote
# View remotes git remote -v # Add remote (usually auto-configured by git clone) git remote add origin https://github.com/user/repo.git # Change remote URL git remote set-url origin https://new-url/repo.git
7.2 Push & Pull
git push
git pull
git fetch
git clone
push = local→remote; pull = remote→local (auto-merge); fetch = remote→local (download only). Always git pull before starting work to minimize conflicts.
8. History & Rollback
git log
git show
git reset
git revert
reset --hard rewrites history and permanently loses code — only use for local, unpushed commits. revert creates a new commit to undo — safe for pushed/shared branches.
9. Stash & Clean
git stash
git stash pop / apply
git clean
main to fix an urgent bug. git stash → git checkout main → fix bug → git checkout feature → git stash pop.
10. Merge & Conflict Resolution
10.1 Merge Methods
git merge
git rebase
10.2 Conflict Resolution
When two branches modify the same lines in the same file, Git cannot auto-merge → CONFLICT.
- Check conflicted files git status Shows “both modified” for conflicted files
-
Open conflicted file, find markers
<<<<<<< HEAD(your changes),=======(divider),>>>>>>> incoming(their changes) - Edit to keep correct content, remove all conflict markers VS Code provides visual conflict resolution (Accept Current / Incoming / Both)
- Mark resolved and commit git add . git commit -m “resolve merge conflict”
11. Advanced Tips
git cherry-pick
git tag
git bisect
git blame
12. Recommended Workflows
12.1 Personal Projects
12.2 Team Collaboration (Feature Branch Workflow)
- Create a feature branch from main git checkout main git pull git checkout -b feature/user-auth
- Develop and commit on the feature branch git add . git commit -m “feat: add user authentication” Multiple commits are fine
- Push the feature branch to remote git push -u origin feature/user-auth
- Create a Pull Request on GitHub/GitLab Team reviews code, then merges after approval
- Delete the feature branch after merge git checkout main git pull git branch -d feature/user-auth
12.3 Command Cheat Sheet
| Scenario | Command |
|---|---|
| Init repo | git init |
| Clone repo | git clone <url> |
| Check status | git status |
| Stage changes | git add . |
| Commit | git commit -m "msg" |
| Push to remote | git push |
| Pull remote changes | git pull |
| Create branch | git checkout -b <branch> |
| Switch branch | git checkout <branch> |
| Merge branch | git merge <branch> |
| View log | git log --oneline |
| Undo last commit (keep changes) | git reset --soft HEAD~1 |
| Revert a commit (safe) | git revert <hash> |
| Stash changes | git stash |
| Restore stash | git stash pop |
