Git 完全指南(小白版)
Git 是最流行的版本控制系统,用于跟踪代码变更、协作开发。本文档提供详细的Git操作指南,包含命令解释和实际案例,让小白也能快速上手。
目录
什么是Git
简单理解
Git = 代码的"时光机"
- 📸 快照功能:记录代码的每个版本
- 🔄 版本管理:可以回到任意历史版本
- 👥 协作工具:多人可以同时编辑代码
- 🌿 分支功能:可以创建多个版本线
核心概念
仓库(Repository):存放代码的地方
提交(Commit):代码的一个快照
分支(Branch):代码的不同版本线
远程(Remote):网络上的代码仓库
Git vs 其他工具
| 特性 | Git | SVN | 文件备份 |
|---|---|---|---|
| 分布式 | ✅ | ❌ | ❌ |
| 离线工作 | ✅ | ❌ | ✅ |
| 分支管理 | ✅ 强大 | ⚠️ 较弱 | ❌ |
| 速度 | ✅ 快 | ⚠️ 中等 | ✅ |
| 学习曲线 | ⚠️ 中等 | ✅ 简单 | ✅ 简单 |
安装Git
Windows系统
方法1:官方安装包
步骤:
1. 访问 https://git-scm.com/download/win
2. 下载安装包(.exe文件)
3. 运行安装程序
4. 一路"下一步"(使用默认设置即可)
5. 完成安装
方法2:使用包管理器
# 使用 Chocolatey
choco install git
# 使用 Scoop
scoop install git
macOS系统
方法1:使用Homebrew(推荐)
# 安装Homebrew(如果还没有)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安装Git
brew install git
方法2:Xcode Command Line Tools
xcode-select --install
Linux系统
Ubuntu/Debian:
sudo apt update
sudo apt install git
CentOS/RHEL:
sudo yum install git
# 或
sudo dnf install git
验证安装
# 检查Git版本
git --version
# 应该显示类似:
# git version 2.39.0
初次配置
配置用户信息
必须配置(首次使用):
# 设置用户名
git config --global user.name "你的名字"
# 设置邮箱
git config --global user.email "your.email@example.com"
# 查看配置
git config --global --list
示例:
git config --global user.name "张三"
git config --global user.email "zhangsan@example.com"
其他常用配置
# 设置默认编辑器(可选)
git config --global core.editor "code --wait" # VS Code
git config --global core.editor "vim" # Vim
# 设置默认分支名(Git 2.28+)
git config --global init.defaultBranch main
# 启用颜色显示
git config --global color.ui auto
# 设置默认推送方式
git config --global push.default simple
查看配置
# 查看所有配置
git config --list
# 查看全局配置
git config --global --list
# 查看本地配置
git config --local --list
# 查看特定配置项
git config user.name
git config user.email
基础操作
创建仓库
方法1:初始化新仓库
# 在项目目录中初始化
cd my-project
git init
# 输出:
# Initialized empty Git repository in /path/to/my-project/.git/
实际案例:
# 创建新项目
mkdir my-first-project
cd my-first-project
# 初始化Git仓库
git init
# 创建README文件
echo "# My First Project" > README.md
# 查看状态
git status
方法2:克隆现有仓库
# 克隆远程仓库
git clone https://github.com/username/repository.git
# 克隆到指定目录
git clone https://github.com/username/repository.git my-project
# 克隆特定分支
git clone -b branch-name https://github.com/username/repository.git
实际案例:
# 克隆一个开源项目
git clone https://github.com/octocat/Hello-World.git
# 进入项目目录
cd Hello-World
# 查看文件
ls -la
查看状态
# 查看工作区状态
git status
# 简短格式
git status -s
git status --short
状态说明:
?? - 未跟踪的文件(新文件)
A - 已添加到暂存区
M - 已修改
D - 已删除
R - 已重命名
实际案例:
# 创建新文件
echo "Hello Git" > hello.txt
# 查看状态
git status
# 输出:
# On branch main
#
# No commits yet
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# hello.txt
#
# nothing added to commit but untracked files present (use "git add" to track)
添加文件到暂存区
# 添加单个文件
git add filename.txt
# 添加所有文件
git add .
# 添加特定类型文件
git add *.js
git add src/
# 交互式添加
git add -i
git add --interactive
# 添加所有修改(包括删除)
git add -A
git add --all
实际案例:
# 创建多个文件
echo "File 1" > file1.txt
echo "File 2" > file2.txt
echo "File 3" > file3.txt
# 添加单个文件
git add file1.txt
git status
# 输出:file1.txt 在暂存区
# 添加所有文件
git add .
git status
# 输出:所有文件都在暂存区
提交更改
# 提交(会打开编辑器输入提交信息)
git commit
# 提交并添加提交信息
git commit -m "提交信息"
# 提交并添加详细描述
git commit -m "标题" -m "详细描述"
# 提交所有已跟踪文件的修改(跳过git add)
git commit -a -m "提交信息"
git commit --all -m "提交信息"
# 修改最后一次提交
git commit --amend
提交信息规范:
格式:<type>(<scope>): <subject>
类型(type):
- feat: 新功能
- fix: 修复bug
- docs: 文档更新
- style: 代码格式
- refactor: 重构
- test: 测试
- chore: 构建/工具
示例:
feat: 添加用户登录功能
fix: 修复支付页面bug
docs: 更新README文档
实际案例:
# 第一次提交
git add .
git commit -m "feat: 初始化项目"
# 修改文件后提交
echo "New content" >> README.md
git add README.md
git commit -m "docs: 更新README文档"
# 查看提交历史
git log
查看提交历史
# 查看提交历史
git log
# 单行显示
git log --oneline
# 图形化显示
git log --graph
# 显示最近N条
git log -5
# 显示统计信息
git log --stat
# 显示文件变更
git log -p
# 搜索提交
git log --grep="关键词"
git log --author="作者名"
实际案例:
# 查看提交历史
git log
# 输出:
# commit abc123def456...
# Author: 张三 <zhangsan@example.com>
# Date: Mon Jan 1 12:00:00 2024 +0800
#
# feat: 添加用户登录功能
#
# commit def456ghi789...
# Author: 张三 <zhangsan@example.com>
# Date: Sun Dec 31 12:00:00 2023 +0800
#
# docs: 更新README文档
# 单行显示
git log --oneline
# 输出:
# abc123 feat: 添加用户登录功能
# def456 docs: 更新README文档
撤销操作
撤销工作区修改
# 撤销单个文件的修改
git checkout -- filename.txt
# 撤销所有修改
git checkout -- .
# 新版本Git使用
git restore filename.txt
git restore .
实际案例:
# 修改文件
echo "Wrong content" > file.txt
# 查看状态
git status
# 显示:file.txt 已修改
# 撤销修改
git restore file.txt
# 再次查看
git status
# 显示:工作区干净
撤销暂存区文件
# 从暂存区移除文件(保留工作区修改)
git reset HEAD filename.txt
# 新版本Git使用
git restore --staged filename.txt
实际案例:
# 添加文件到暂存区
git add file.txt
# 查看状态
git status
# 显示:file.txt 在暂存区
# 从暂存区移除
git restore --staged file.txt
# 查看状态
git status
# 显示:file.txt 已修改但未暂存
修改最后一次提交
# 修改提交信息
git commit --amend -m "新的提交信息"
# 添加文件到上次提交
git add forgotten-file.txt
git commit --amend --no-edit
实际案例:
# 提交
git commit -m "fix: 修复bug"
# 发现提交信息有误,修改
git commit --amend -m "fix: 修复登录页面的bug"
# 忘记添加文件,添加到上次提交
git add missing-file.txt
git commit --amend --no-edit
分支管理
什么是分支
分支 = 代码的平行宇宙
主分支(main/master):
A --- B --- C --- D
↑
当前版本
功能分支(feature):
A --- B --- C --- D (main)
\
E --- F (feature)
↑
新功能开发
创建和切换分支
# 创建分支
git branch branch-name
# 创建并切换到新分支
git checkout -b branch-name
git switch -c branch-name # 新命令
# 切换到分支
git checkout branch-name
git switch branch-name # 新命令
# 查看所有分支
git branch
# 查看远程分支
git branch -r
# 查看所有分支(包括远程)
git branch -a
实际案例:
# 查看当前分支
git branch
# 输出:* main
# 创建功能分支
git checkout -b feature/login
# 查看分支
git branch
# 输出:
# main
# * feature/login (当前分支)
# 在新分支上工作
echo "Login feature" > login.js
git add login.js
git commit -m "feat: 添加登录功能"
# 切换回主分支
git checkout main
合并分支
# 合并分支到当前分支
git merge branch-name
# 合并时创建合并提交
git merge --no-ff branch-name
# 合并时只允许快进
git merge --ff-only branch-name
实际案例:
# 在main分支
git checkout main
# 合并feature/login分支
git merge feature/login
# 输出:
# Updating abc123..def456
# Fast-forward
# login.js | 1 +
# 1 file changed, 1 insertion(+)
# 查看提交历史
git log --oneline --graph
# 输出:
# * def456 feat: 添加登录功能
# * abc123 docs: 更新README
删除分支
# 删除本地分支
git branch -d branch-name
# 强制删除(即使未合并)
git branch -D branch-name
# 删除远程分支
git push origin --delete branch-name
实际案例:
# 功能已完成并合并
git merge feature/login
# 删除功能分支
git branch -d feature/login
# 输出:
# Deleted branch feature/login (was def456).
分支策略
Git Flow(推荐):
main/master - 生产环境代码
develop - 开发主分支
feature/* - 功能分支
release/* - 发布分支
hotfix/* - 紧急修复分支
实际工作流:
# 1. 从develop创建功能分支
git checkout develop
git pull
git checkout -b feature/user-profile
# 2. 开发功能
# ... 编写代码 ...
git add .
git commit -m "feat: 添加用户资料功能"
# 3. 推送到远程
git push origin feature/user-profile
# 4. 创建Pull Request(在GitHub/GitLab上)
# 5. 合并后删除分支
git checkout develop
git pull
git branch -d feature/user-profile
远程仓库
添加远程仓库
# 添加远程仓库
git remote add origin https://github.com/username/repo.git
# 查看远程仓库
git remote
# 查看远程仓库URL
git remote -v
# 修改远程仓库URL
git remote set-url origin new-url
# 删除远程仓库
git remote remove origin
实际案例:
# 在GitHub上创建新仓库后
git remote add origin https://github.com/username/my-project.git
# 查看
git remote -v
# 输出:
# origin https://github.com/username/my-project.git (fetch)
# origin https://github.com/username/my-project.git (push)
推送代码
# 推送到远程(首次)
git push -u origin main
git push --set-upstream origin main
# 后续推送
git push
# 推送特定分支
git push origin branch-name
# 推送所有分支
git push --all
# 推送标签
git push --tags
实际案例:
# 首次推送
git push -u origin main
# 输出:
# Enumerating objects: 5, done.
# Counting objects: 100% (5/5), done.
# Writing objects: 100% (5/5), 432 bytes | 432.00 KiB/s, done.
# Total 5 (delta 0), reused 0 (delta 0)
# To https://github.com/username/my-project.git
# * [new branch] main -> main
# Branch 'main' set up to track remote branch 'main' from 'origin'.
# 后续修改后推送
echo "New feature" > feature.txt
git add feature.txt
git commit -m "feat: 添加新功能"
git push
拉取代码
# 拉取并合并
git pull
# 拉取特定分支
git pull origin branch-name
# 只拉取不合并
git fetch
# 拉取所有远程分支
git fetch --all
实际案例:
# 拉取最新代码
git pull
# 输出:
# remote: Enumerating objects: 5, done.
# remote: Counting objects: 100% (5/5), done.
# remote: Compressing objects: 100% (3/3), done.
# remote: Total 3 (delta 0), reused 0 (delta 0)
# Unpacking objects: 100% (3/3), done.
# From https://github.com/username/my-project
# abc123..def456 main -> origin/main
# Updating abc123..def456
# Fast-forward
# new-file.txt | 1 +
# 1 file changed, 1 insertion(+)
解决冲突
冲突场景:
本地修改:
第10行:console.log("本地修改");
远程修改:
第10行:console.log("远程修改");
解决步骤:
# 1. 拉取时出现冲突
git pull
# 输出:
# Auto-merging file.js
# CONFLICT (content): Merge conflict in file.js
# Automatic merge failed; fix conflicts and then commit the result.
# 2. 查看冲突文件
git status
# 显示:file.js 有冲突
# 3. 打开文件查看冲突标记
cat file.js
# 输出:
# <<<<<<< HEAD
# console.log("本地修改");
# =======
# console.log("远程修改");
# >>>>>>> origin/main
# 4. 手动解决冲突(编辑文件)
# 选择保留的内容,删除冲突标记
# 5. 标记为已解决
git add file.js
# 6. 完成合并
git commit
常用工作流
工作流1:个人项目
# 1. 初始化项目
git init
git add .
git commit -m "feat: 初始化项目"
# 2. 添加远程仓库
git remote add origin https://github.com/username/repo.git
# 3. 推送代码
git push -u origin main
# 4. 日常开发
git add .
git commit -m "feat: 添加新功能"
git push
工作流2:团队协作
# 1. 克隆项目
git clone https://github.com/team/project.git
cd project
# 2. 创建功能分支
git checkout -b feature/my-feature
# 3. 开发功能
# ... 编写代码 ...
git add .
git commit -m "feat: 我的功能"
# 4. 推送分支
git push origin feature/my-feature
# 5. 在GitHub上创建Pull Request
# 6. 代码审查通过后合并
# 7. 更新本地代码
git checkout main
git pull
# 8. 删除功能分支
git branch -d feature/my-feature
工作流3:修复Bug
# 1. 从main创建hotfix分支
git checkout main
git pull
git checkout -b hotfix/critical-bug
# 2. 修复bug
# ... 修复代码 ...
git add .
git commit -m "fix: 修复严重bug"
# 3. 推送到远程
git push origin hotfix/critical-bug
# 4. 合并到main
git checkout main
git merge hotfix/critical-bug
git push
# 5. 也合并到develop(如果有)
git checkout develop
git merge hotfix/critical-bug
git push
# 6. 删除hotfix分支
git branch -d hotfix/critical-bug
高级操作
标签管理
# 创建标签
git tag v1.0.0
# 创建带注释的标签
git tag -a v1.0.0 -m "版本1.0.0发布"
# 查看标签
git tag
# 查看标签信息
git show v1.0.0
# 删除标签
git tag -d v1.0.0
# 推送标签
git push origin v1.0.0
git push --tags
实际案例:
# 发布版本
git tag -a v1.0.0 -m "第一个正式版本"
# 查看
git tag
# 输出:v1.0.0
# 推送到远程
git push origin v1.0.0
暂存更改
# 暂存当前更改
git stash
# 暂存并添加描述
git stash save "描述信息"
# 查看暂存列表
git stash list
# 应用暂存(保留stash)
git stash apply
# 应用并删除stash
git stash pop
# 删除stash
git stash drop
# 清空所有stash
git stash clear
实际案例:
# 正在开发功能A
echo "Feature A" > feature-a.txt
git add feature-a.txt
# 突然需要切换到其他分支修复bug
git stash
# 输出:Saved working directory and index state
# 切换到其他分支
git checkout main
# 修复bug后回到原分支
git checkout feature-a
git stash pop
# 恢复之前的更改
查看差异
# 查看工作区与暂存区的差异
git diff
# 查看暂存区与仓库的差异
git diff --staged
git diff --cached
# 查看两次提交的差异
git diff commit1 commit2
# 查看文件变更统计
git diff --stat
实际案例:
# 修改文件
echo "New line" >> file.txt
# 查看差异
git diff
# 输出:
# diff --git a/file.txt b/file.txt
# index abc123..def456 100644
# --- a/file.txt
# +++ b/file.txt
# @@ -1 +1,2 @@
# Original line
# +New line
回退版本
# 回退到指定提交(保留工作区)
git reset --soft commit-hash
# 回退到指定提交(保留工作区,清空暂存区)
git reset --mixed commit-hash
git reset commit-hash
# 回退到指定提交(完全回退)
git reset --hard commit-hash
# 查看提交历史(找到commit-hash)
git log --oneline
实际案例:
# 查看提交历史
git log --oneline
# 输出:
# abc123 feat: 新功能
# def456 fix: 修复bug
# ghi789 docs: 更新文档
# 回退到def456(保留工作区)
git reset --soft def456
# 查看状态
git status
# 显示:新功能的更改在暂存区
# 完全回退
git reset --hard def456
# 警告:会丢失所有未提交的更改
查看文件历史
# 查看文件的提交历史
git log filename.txt
# 查看文件的具体变更
git log -p filename.txt
# 查看谁修改了文件的哪一行
git blame filename.txt
常见问题
Q1: 如何撤销已推送的提交?
方法1:使用revert(推荐,安全)
# 创建新提交来撤销指定提交
git revert commit-hash
git push
方法2:使用reset(危险,需要强制推送)
# 回退本地
git reset --hard commit-hash
# 强制推送(会覆盖远程历史)
git push --force
# 警告:不要在主分支使用!
Q2: 如何忽略文件?
创建.gitignore文件:
# 忽略单个文件
echo "secret.txt" > .gitignore
# 忽略整个目录
echo "node_modules/" >> .gitignore
# 忽略特定类型文件
echo "*.log" >> .gitignore
# 忽略但保留文件(已跟踪的文件)
git rm --cached file.txt
.gitignore示例:
# 依赖目录
node_modules/
vendor/
# 日志文件
*.log
logs/
# 环境变量
.env
.env.local
# 编译文件
dist/
build/
*.class
# 系统文件
.DS_Store
Thumbs.db
Q3: 如何查看某个文件的修改历史?
# 查看文件的提交历史
git log -- filename.txt
# 查看文件的具体变更
git log -p -- filename.txt
# 查看文件的每一行是谁修改的
git blame filename.txt
Q4: 如何合并多个提交?
# 交互式rebase(合并最近3个提交)
git rebase -i HEAD~3
# 在编辑器中:
# pick abc123 第一个提交
# squash def456 第二个提交
# squash ghi789 第三个提交
# 保存后会打开编辑器编辑合并后的提交信息
Q5: 如何查看远程仓库信息?
# 查看远程仓库
git remote -v
# 查看远程分支
git branch -r
# 查看远程仓库的详细信息
git remote show origin
Q6: 如何克隆特定分支?
# 克隆并切换到指定分支
git clone -b branch-name https://github.com/user/repo.git
# 克隆后切换分支
git clone https://github.com/user/repo.git
cd repo
git checkout branch-name
Q7: 如何设置Git代理?
# HTTP代理
git config --global http.proxy http://proxy.example.com:8080
git config --global https.proxy https://proxy.example.com:8080
# SOCKS5代理
git config --global http.proxy socks5://127.0.0.1:1080
# 取消代理
git config --global --unset http.proxy
git config --global --unset https.proxy
Q8: 如何查看Git配置?
# 查看所有配置
git config --list
# 查看全局配置
git config --global --list
# 查看特定配置项
git config user.name
git config user.email
# 编辑配置文件
git config --global --edit
实用技巧
别名设置
# 设置常用命令的别名
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
# 使用别名
git st # 等同于 git status
git co main # 等同于 git checkout main
常用别名推荐
# 更简洁的日志
git config --global alias.lg "log --oneline --graph --decorate --all"
# 查看最后一次提交
git config --global alias.last "log -1 HEAD"
# 撤销暂存
git config --global alias.unstage "reset HEAD --"
# 查看简短的统计
git config --global alias.stats "log --stat"
快速参考
初始化:
git init # 初始化仓库
git clone <url> # 克隆仓库
基本操作:
git add <file> # 添加到暂存区
git commit -m "消息" # 提交
git status # 查看状态
git log # 查看历史
分支操作:
git branch # 查看分支
git checkout -b <name> # 创建并切换分支
git merge <branch> # 合并分支
远程操作:
git remote add <name> <url> # 添加远程
git push # 推送
git pull # 拉取
总结
核心命令
- 初始化:
git init,git clone - 基本操作:
git add,git commit,git status - 分支管理:
git branch,git checkout,git merge - 远程操作:
git remote,git push,git pull
最佳实践
✓ 提交信息要清晰明确
✓ 经常提交,小步快跑
✓ 使用分支开发新功能
✓ 推送前先拉取最新代码
✓ 定期备份重要代码
✓ 使用.gitignore忽略不需要的文件
学习路径
1. 基础操作(add, commit, status)
2. 分支管理(branch, checkout, merge)
3. 远程操作(remote, push, pull)
4. 高级功能(stash, rebase, cherry-pick)
5. 团队协作(Pull Request, Code Review)
记住:Git是一个强大的工具,多练习就能熟练掌握。遇到问题可以查看 git help <command> 获取帮助! 🚀
评论区