Git 完全教程

Git 完全教程 · Complete Git Guide

Git 完全教程

从零开始理解 Git:它是什么、为什么需要它、核心概念、常用命令与实战工作流

一、什么是 Git

Git 是一个分布式版本控制系统(Distributed Version Control System),由 Linus Torvalds 于 2005 年创建,最初用于管理 Linux 内核的源代码。

关键特性

分布式:每个人的本地电脑都拥有完整的仓库副本(包括所有历史记录),不依赖中央服务器即可工作。

快照式存储:Git 不是记录文件的差异,而是每次提交都保存完整的文件快照。未变更的文件会以指针引用之前的版本,既高效又可靠。

几乎所有的操作都在本地执行:查看日志、创建分支、提交代码等操作无需网络连接,速度极快。

数据完整性保障:每个文件的内容都通过 SHA-1 哈希值校验,任何篡改都会被立刻发现。

一句话总结:Git 就像一个”时光机”——它能记录代码的每一次变更历史,随时回到过去的任意版本,还能让多人同时开发同一项目而不互相冲突。

二、为什么需要 Git

没有 Git 的世界

假设没有版本控制,开发者通常的做法是手动复制文件夹并重命名:project_v1project_v2project_finalproject_final_v2…… 这种方式存在严重问题:

  • 无法追溯每个版本具体改了什么
  • 多人协作时容易覆盖彼此的代码
  • 误删文件后无法恢复
  • 文件名混乱、版本关系不清晰
  • 浪费大量磁盘空间(每次都是完整复制)

Git 解决的核心问题

版本追踪

完整记录每次改动的谁、什么时间、改了什么内容,随时查看差异对比。

多人协作

分支(Branch)机制让多人可以并行开发不同功能,最终合并到一起。

随时回退

发现严重 Bug 可以一键回退到之前的稳定版本,不用担心误操作。

代码备份

推送到远程仓库(GitHub/GitLab)后,即使本地电脑损坏,代码也不会丢失

三、核心概念

3.1 Git 的四个区域

工作区
Working Dir
git add 暂存区
Staging Area
git commit 本地仓库
Local Repo
git push 远程仓库
Remote Repo
理解这四个区域是掌握 Git 的关键。
工作区 = 电脑上看到的文件;暂存区 = 准备提交的改动清单;本地仓库 = 本地的版本数据库;远程仓库 = GitHub/GitLab 上的服务器端仓库。

3.2 仓库(Repository / Repo)

仓库是 Git 管理的基本单元。一个仓库对应一个项目,包含该项目的所有文件、版本历史、分支等信息。通过 git initgit 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.0v2.1.3

四、安装与初始配置

4.1 安装 Git

Windows

winget install Git.Git
或从 git-scm.com 下载安装包

macOS

brew install git
或安装 Xcode Command Line Tools

Linux (Debian/Ubuntu)

sudo apt install git
或使用各发行版的包管理器

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 文件状态生命周期

Untracked
未追踪
git add Staged
已暂存
git commit Committed
已提交

git status

git status
查看当前工作区和暂存区状态:哪些文件被修改、哪些已暂存、哪些未追踪

git add

git add . # 添加所有变更 git add file.py # 添加指定文件
将文件从工作区移到暂存区

git commit

git commit -m “feat: add login page”
将暂存区的改动提交到本地仓库,-m 指定提交信息

git diff

git diff # 工作区 vs 暂存区 git diff –staged # 暂存区 vs 最新提交
查看文件的具体改动内容

5.3 .gitignore 文件

.gitignore 文件指定哪些文件/目录不纳入 Git 管理(如编译产物、系统文件、敏感信息):

# 编译产物
node_modules/
__pycache__/
*.pyc
build/
dist/

# 系统文件
.DS_Store
Thumbs.db

# 环境配置(包含敏感信息)
.env
.env.local

# IDE 配置
.vscode/
.idea/

六、分支管理

分支是 Git 最强大的功能之一——它允许并行开发不同功能,互不干扰。

main feature/login bugfix/fix-crash
← 主分支(稳定代码) ←

git branch

git branch # 查看本地分支 git branch -a # 查看所有分支(含远程) git branch feature/api # 创建新分支
查看和创建分支(不切换)

git checkout / switch

git checkout feature/api # 切换到分支 git switch -c feature/api # 创建并切换(推荐)
切换工作分支。git switch 是新版推荐命令

git merge

git checkout main git merge feature/api # 合并到 main
将指定分支的改动合并到当前分支

git branch -d

git branch -d feature/api # 安全删除(已合并) git branch -D feature/api # 强制删除(未合并也可删)
删除已完成的分支,保持分支列表整洁
分支命名建议:使用有意义的名称,常见前缀: 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 push origin main # 推送到远程 main 分支 git push -u origin main # 首次推送并建立追踪关系 git push # 简写(已有追踪关系时)
将本地提交推送到远程仓库

git pull

git pull origin main # 拉取并自动合并 git pull –rebase origin main # 拉取并变基(保持线性历史)
获取远程最新代码并合并到本地

git fetch

git fetch origin # 获取远程更新(不自动合并)
只下载远程数据,不改变本地分支。适合先查看再决定是否合并

git clone

git clone https://github.com/user/repo.git
克隆远程仓库到本地(自动创建目录、设置 remote)
push vs pull vs fetch:push = 本地→远程;pull = 远程→本地(自动合并);fetch = 远程→本地(仅下载不合并)。建议每次开发前先 git pull,减少冲突。

八、查看历史与回退

git log

git log # 完整日志 git log –oneline # 简洁模式(一行一条) git log –oneline –graph # 图形化分支历史 git log –author=”name” # 按作者过滤 git log –since=”2 weeks ago” # 按时间过滤
查看提交历史

git show

git show abc1234 # 查看某次提交的详情 git show abc1234 –stat # 只看改了哪些文件
查看某次具体提交的内容

git reset

git reset –soft HEAD~1 # 回退提交,保留改动在暂存区 git reset –mixed HEAD~1 # 回退提交,保留改动在工作区(默认) git reset –hard HEAD~1 # 回退提交,丢弃所有改动(危险!)
撤销提交(可指定回退程度)

git revert

git revert abc1234
创建一个新提交来”撤销”指定提交的改动(安全,不改写历史)
reset vs revert:reset --hard 会改写历史并永久丢失代码,仅适用于未推送的本地提交。revert 会创建新的提交来撤销,不改写历史,适合已推送的公共分支。

九、暂存与清理

git stash

git stash # 暂存当前改动 git stash save “msg” # 带备注信息暂存 git stash list # 查看所有暂存
临时保存未提交的改动(切换分支前常用)

git stash pop / apply

git stash pop # 恢复最近的暂存并删除记录 git stash apply stash@{0} # 恢复指定暂存(保留记录) git stash drop stash@{0} # 手动删除暂存记录
恢复之前暂存的改动

git clean

git clean -n # 预览将被清理的文件 git clean -f # 删除未追踪的文件 git clean -fd # 删除未追踪的文件和文件夹
清理工作区中未追踪的文件(不影响已提交的内容)
典型使用场景:正在开发新功能,突然需要切到 main 分支修一个紧急 Bug。用 git stash 暂存当前改动 → git checkout main → 修 Bug → git checkout featuregit stash pop 恢复继续开发。

十、合并与冲突解决

10.1 合并方式

git merge(合并提交)

git checkout main git merge feature/api
保留完整分支历史,创建一个合并提交节点

git rebase(变基)

git checkout feature/api git rebase main
将当前分支的提交”重放”到目标分支最新提交之上,历史更线性。⚠️ 不要对已推送的公共分支执行 rebase

10.2 冲突解决流程

当两个分支修改了同一文件的同一位置时,Git 无法自动合并,产生冲突(CONFLICT)。

  1. Git 会标记冲突文件 git status 冲突文件显示为 “both modified”
  2. 打开冲突文件,搜索冲突标记 <<<<<<< HEAD(当前分支改动)和 =======(分隔线)和 >>>>>>> incoming(另一分支改动)
  3. 手动编辑保留正确内容,删除所有冲突标记 VS Code 等编辑器提供可视化冲突解决界面(Accept Current / Incoming / Both)
  4. 标记冲突已解决并提交 git add .  git commit -m “resolve merge conflict in config.py”

十一、高级技巧

git cherry-pick

git cherry-pick abc1234
将某个提交”摘”到当前分支,不需要合并整个分支

git tag

git tag v1.0.0 # 轻量标签 git tag -a v1.0.0 -m “Release 1.0” # 附注标签 git push origin v1.0.0 # 推送标签到远程 git tag -d v1.0.0 # 删除本地标签
标记版本发布点

git bisect

git bisect start git bisect bad # 当前版本有 Bug git bisect good abc1234 # 这个版本没有 Bug
二分查找定位引入 Bug 的提交(自动跳转中间版本)

git blame

git blame file.py git blame -L 10,20 file.py
查看文件每一行最后是谁在什么时候修改的

十二、推荐工作流

12.1 个人项目

git pull 写代码 git add . git commit -m git push

12.2 团队协作(Feature Branch Workflow)

  1. 从 main 创建功能分支 git checkout main  git pull  git checkout -b feature/user-auth
  2. 在功能分支上开发和提交 git add .  git commit -m “feat: add user authentication” 可以多次 commit
  3. 推送功能分支到远程 git push -u origin feature/user-auth
  4. 在 GitHub/GitLab 上创建 Pull Request (PR) 团队成员 Code Review 通过后合并
  5. 合并后删除功能分支 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

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.

In a nutshell: Git is like a “time machine” for your code — it records every change, lets you travel back to any previous version at any time, and enables multiple people to work on the same project simultaneously without conflicts.

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

Working Dir git add Staging Area git commit Local Repo git push Remote Repo
Understanding these four areas is the key to mastering Git.
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

Windows

winget install Git.Git
Or download from git-scm.com

macOS

brew install git
Or install Xcode Command Line Tools

Linux (Debian/Ubuntu)

sudo apt install git
Or use your distro’s package manager

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
Tip:--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

Untracked git add Staged git commit Committed

git status

git status
Show working tree status: modified files, staged files, untracked files

git add

git add . # Stage all changes git add file.py # Stage specific file
Move files from working dir to staging area

git commit

git commit -m “feat: add login page”
Commit staged changes to local repo. -m specifies the message.

git diff

git diff # Working dir vs staging git diff –staged # Staging vs last commit
View detailed changes in files

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 branch # List local branches git branch -a # List all (including remote) git branch feature/api # Create branch
View and create branches (without switching)

git checkout / switch

git checkout feature/api # Switch to branch git switch -c feature/api # Create + switch (recommended)
Switch working branch. git switch is the modern recommended command.

git merge

git checkout main git merge feature/api
Merge target branch into current branch

git branch -d

git branch -d feature/api # Safe delete (merged) git branch -D feature/api # Force delete (even unmerged)
Delete finished branches to keep things tidy
Naming convention: Use descriptive names with prefixes: 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 push origin main # Push to remote main git push -u origin main # First push + set tracking git push # Shortcut (with tracking)
Push local commits to remote

git pull

git pull origin main # Pull + auto-merge git pull –rebase origin main # Pull + rebase
Fetch remote changes and merge into local

git fetch

git fetch origin
Download remote data without auto-merging. Good for reviewing before merging.

git clone

git clone https://github.com/user/repo.git
Clone remote repo locally (auto-creates directory and sets remote)
push vs pull vs fetch: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 log –oneline –graph git log –author=”name” git log –since=”2 weeks ago”
View commit history

git show

git show abc1234 git show abc1234 –stat
View details of a specific commit

git reset

git reset –soft HEAD~1 # Keep changes staged git reset –mixed HEAD~1 # Keep changes in working dir git reset –hard HEAD~1 # Discard all changes (danger!)
Undo commits (with varying levels of preservation)

git revert

git revert abc1234
Create a new commit that undoes a previous commit (safe, doesn’t rewrite history)
reset vs 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 git stash save “WIP: login form” git stash list
Temporarily save uncommitted changes

git stash pop / apply

git stash pop # Restore + remove git stash apply stash@{0} # Restore + keep git stash drop stash@{0} # Remove stash
Restore previously stashed changes

git clean

git clean -n # Preview git clean -f # Delete untracked files git clean -fd # Delete files + folders
Remove untracked files from working directory
Typical scenario:Working on a feature, need to switch to main to fix an urgent bug. git stashgit checkout main → fix bug → git checkout featuregit stash pop.

10. Merge & Conflict Resolution

10.1 Merge Methods

git merge

git checkout main git merge feature/api
Creates a merge commit node, preserving full branch history

git rebase

git checkout feature/api git rebase main
Replays commits on top of target branch for linear history. ⚠️ Never rebase shared/public branches.

10.2 Conflict Resolution

When two branches modify the same lines in the same file, Git cannot auto-merge → CONFLICT.

  1. Check conflicted files git status Shows “both modified” for conflicted files
  2. Open conflicted file, find markers <<<<<<< HEAD (your changes), ======= (divider), >>>>>>> incoming (their changes)
  3. Edit to keep correct content, remove all conflict markers VS Code provides visual conflict resolution (Accept Current / Incoming / Both)
  4. Mark resolved and commit git add .  git commit -m “resolve merge conflict”

11. Advanced Tips

git cherry-pick

git cherry-pick abc1234
Apply a specific commit to the current branch without merging the whole branch

git tag

git tag v1.0.0 git tag -a v1.0.0 -m “Release 1.0” git push origin v1.0.0 git tag -d v1.0.0
Mark release points

git bisect

git bisect start git bisect bad git bisect good abc1234
Binary search to find the commit that introduced a bug

git blame

git blame file.py git blame -L 10,20 file.py
See who last modified each line and when

12. Recommended Workflows

12.1 Personal Projects

git pull Code git add . git commit -m git push

12.2 Team Collaboration (Feature Branch Workflow)

  1. Create a feature branch from main git checkout main  git pull  git checkout -b feature/user-auth
  2. Develop and commit on the feature branch git add .  git commit -m “feat: add user authentication” Multiple commits are fine
  3. Push the feature branch to remote git push -u origin feature/user-auth
  4. Create a Pull Request on GitHub/GitLab Team reviews code, then merges after approval
  5. Delete the feature branch after merge git checkout main  git pull  git branch -d feature/user-auth

12.3 Command Cheat Sheet

ScenarioCommand
Init repogit init
Clone repogit clone <url>
Check statusgit status
Stage changesgit add .
Commitgit commit -m "msg"
Push to remotegit push
Pull remote changesgit pull
Create branchgit checkout -b <branch>
Switch branchgit checkout <branch>
Merge branchgit merge <branch>
View loggit log --oneline
Undo last commit (keep changes)git reset --soft HEAD~1
Revert a commit (safe)git revert <hash>
Stash changesgit stash
Restore stashgit stash pop