git使用指南
概述
Git是一个分布式版本控制系统,用于跟踪文件的变化,协调多人协作开发。它具有速度快、数据完整性高、支持非线性开发等特点。
Git 基础概念
仓库(Repository)
- 本地仓库:存储在本地计算机上的Git仓库
- 远程仓库:存储在远程服务器上的Git仓库(如GitHub、GitLab)
工作区域
- 工作区(Working Directory):实际操作的文件目录
- 暂存区(Staging Area):临时存放修改的地方
- 版本库(Repository):存储提交历史的地方
文件状态
- 未跟踪(Untracked):新创建的文件,Git未管理
- 已修改(Modified):文件已修改但未暂存
- 已暂存(Staged):文件已放入暂存区
- 已提交(Committed):文件已提交到版本库
Git 安装与配置
安装 Git
# Windows
# 下载安装包:https://git-scm.com/download/win
# macOS
brew install git
# Ubuntu/Debian
sudo apt update
sudo apt install git
# CentOS/RHEL
sudo yum install git
# 或
sudo dnf install git
# 验证安装
git --version
基础配置
# 全局用户信息配置
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# 查看配置
git config --list
git config user.name
git config user.email
# 编辑配置文件
git config --global --edit
# 设置默认编辑器
git config --global core.editor "vim"
git config --global core.editor "code --wait" # VS Code
# 设置默认分支名
git config --global init.defaultBranch main
# 设置换行符处理
git config --global core.autocrlf true # Windows
git config --global core.autocrlf input # Linux/macOS
git config --global core.autocrlf false # 不自动转换
# 设置文件权限
git config --global core.filemode false # 忽略文件权限变化
# 设置推送策略
git config --global push.default simple # 推送当前分支到同名远程分支
仓库操作
创建仓库
# 初始化新仓库
git init
git init my-project # 在指定目录创建
# 克隆远程仓库
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git my-project # 指定目录名
git clone git@github.com:user/repo.git # SSH协议
# 克隆特定分支
git clone -b develop https://github.com/user/repo.git
git clone --branch feature/new-feature https://github.com/user/repo.git
# 浅克隆(只获取最新提交)
git clone --depth 1 https://github.com/user/repo.git
# 裸克隆(用于创建镜像)
git clone --bare https://github.com/user/repo.git
仓库状态查看
# 查看仓库状态
git status
git status -s # 简短格式
git status --porcelain # 脚本友好的格式
# 查看文件状态
git status --ignored # 包含被忽略的文件
git status --untracked-files=no # 不显示未跟踪文件
# 查看仓库信息
git log --oneline --graph --decorate # 图形化显示提交历史
git log --stat # 显示文件变更统计
git log --patch # 显示具体变更内容
基础文件操作
添加文件
# 添加单个文件
git add file.txt
git add README.md
# 添加多个文件
git add file1.txt file2.txt
# 添加目录
git add src/
git add . # 添加当前目录所有文件
git add --all # 添加所有变更文件
git add -A # 同上
# 交互式添加
git add -i
git add --interactive
# 添加部分修改
git add -p file.txt # 逐块选择修改
git add --patch file.txt
# 忽略文件变更
git add --intent-to-add file.txt # 标记为待添加但不实际添加内容
提交操作
# 基本提交
git commit -m "Initial commit"
# 提交并添加所有变更
git commit -am "Fix bug in user module"
# 详细提交信息
git commit
# 会打开编辑器输入详细提交信息
# 修改最后一次提交
git commit --amend
git commit --amend -m "Updated commit message"
# 空提交(用于触发CI等)
git commit --allow-empty -m "Trigger CI"
# 签名提交(需要GPG密钥)
git commit -S -m "Signed commit"
# 指定作者
git commit --author="John Doe <john@example.com>" -m "Commit by John"
文件删除与重命名
# 删除文件
git rm file.txt
git rm -r directory/ # 删除目录
# 删除但保留本地文件
git rm --cached file.txt
# 强制删除
git rm -f file.txt
# 重命名/移动文件
git mv old.txt new.txt
git mv file.txt directory/
git mv old-dir/ new-dir/
# 查看重命名历史
git log --follow -- file.txt
git log --stat -- file.txt
分支管理
分支基础操作
# 查看分支
git branch # 查看本地分支
git branch -r # 查看远程分支
git branch -a # 查看所有分支
git branch -v # 查看分支及最新提交
git branch --merged # 查看已合并分支
git branch --no-merged # 查看未合并分支
# 创建分支
git branch feature-new # 创建新分支
git branch feature-new main # 基于main分支创建
# 切换分支
git checkout feature-new
git switch feature-new # Git 2.23+
git checkout -b feature-new # 创建并切换
git switch -c feature-new # Git 2.23+
# 重命名分支
git branch -m old-name new-name
git branch --move old-name new-name
# 删除分支
git branch -d feature-new # 删除已合并分支
git branch -D feature-new # 强制删除分支
git push origin --delete feature-new # 删除远程分支
git push origin :feature-new # 同上
# 查看分支关系
git log --oneline --graph --all
git show-branch
分支合并
# 合并分支
git checkout main
git merge feature-new # 普通合并
git merge --no-ff feature-new # 不使用快进合并
git merge --squash feature-new # 压缩合并
# 中断合并
git merge --abort
# 继续合并(解决冲突后)
git merge --continue
# 查看合并历史
git log --merge
git log --first-parent # 只显示主线提交
变基操作
# 基础变基
git checkout feature-new
git rebase main # 将feature-new变基到main
# 交互式变基
git rebase -i HEAD~3 # 修改最近3个提交
git rebase -i main # 修改从main分支分叉后的所有提交
# 变基选项
# p, pick = 使用提交
# r, reword = 使用提交,但修改提交信息
# e, edit = 使用提交,但停止修改
# s, squash = 使用提交,但合并到前一个提交
# f, fixup = 类似squash,但丢弃提交信息
# d, drop = 删除提交
# 继续变基
git rebase --continue
# 中断变基
git rebase --abort
# 跳过当前提交
git rebase --skip
# 变基到指定提交
git rebase --onto main feature-branch~3 feature-branch
远程操作
远程仓库管理
# 查看远程仓库
git remote
git remote -v # 显示详细信息
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git
# 重命名远程仓库
git remote rename origin old-origin
# 删除远程仓库
git remote remove origin
git remote rm origin
# 查看远程仓库信息
git remote show origin
git remote show origin --verbose
# 更改远程仓库URL
git remote set-url origin https://github.com/user/new-repo.git
git remote set-url --push origin https://github.com/user/repo.git
推送与拉取
# 推送到远程仓库
git push origin main # 推送main分支
git push origin feature-new # 推送feature-new分支
git push origin --all # 推送所有分支
git push origin --tags # 推送所有标签
# 设置上游分支
git push -u origin feature-new
git push --set-upstream origin feature-new
# 强制推送
git push --force origin feature-new
git push --force-with-lease origin feature-new # 更安全的强制推送
# 拉取远程更新
git fetch origin # 获取远程更新但不合并
git fetch origin main # 获取特定分支
git fetch --all # 获取所有远程仓库更新
# 拉取并合并
git pull origin main
git pull --rebase origin main # 使用变基方式拉取
# 查看远程分支
git branch -r
git ls-remote origin
查看历史
日志查看
# 基础日志
git log
git log --oneline # 简短格式
git log --graph # 图形化显示
git log --stat # 显示统计信息
git log --patch # 显示具体变更
# 限制显示数量
git log -n 10 # 最近10次提交
git log --since="2023-01-01" # 指定日期之后
git log --until="2023-12-31" # 指定日期之前
git log --author="John Doe" # 指定作者
git log --grep="fix bug" # 搜索提交信息
# 文件历史
git log -- file.txt # 特定文件的历史
git log --follow -- file.txt # 跟踪文件重命名
# 分支比较
git log main..feature-new # feature-new有而main没有的提交
git log main...feature-new # 两个分支的独有提交
git log --left-right main...feature-new # 显示每个提交属于哪个分支
差异比较
# 工作区与暂存区比较
git diff
git diff -- file.txt
# 暂存区与最新提交比较
git diff --cached
git diff --staged # 同上
# 工作区与最新提交比较
git diff HEAD
git diff HEAD~1
# 分支比较
git diff main feature-new
git diff main...feature-new # 比较共同祖先后的差异
# 提交间比较
git diff commit1 commit2
git diff commit1..commit2
git diff commit1...commit2
# 统计信息
git diff --stat
git diff --shortstat
查看特定内容
# 查看提交详情
git show
git show HEAD # 最新提交
git show commit-hash # 特定提交
git show HEAD~2 # 倒数第三个提交
# 查看文件特定版本
git show HEAD:file.txt
git show commit-hash:file.txt
# 查看提交中的文件列表
git show --name-only HEAD
git show --name-status HEAD
# 查看分支信息
git show-branch
git show-branch --more=10
git show-branch main feature-new
撤销操作
撤销工作区修改
# 撤销单个文件修改
git checkout -- file.txt
git restore file.txt # Git 2.23+
# 撤销所有修改
git checkout .
git restore .
# 撤销删除
git checkout -- deleted-file.txt
# 交互式恢复
git restore --interactive
撤销暂存区修改
# 取消暂存单个文件
git reset HEAD file.txt
git restore --staged file.txt # Git 2.23+
# 取消暂存所有文件
git reset HEAD
git restore --staged .
# 重置到特定提交
git reset commit-hash
git reset --soft commit-hash # 保留工作区和暂存区
git reset --mixed commit-hash # 保留工作区(默认)
git reset --hard commit-hash # 重置所有
撤销提交
# 撤销最后一次提交(保留修改)
git reset --soft HEAD~1
# 撤销最后一次提交(丢弃修改)
git reset --hard HEAD~1
# 创建反向提交
git revert HEAD
git revert commit-hash
# 撤销多个提交
git revert HEAD~3..HEAD
git revert --no-commit HEAD~3..HEAD # 不自动提交
标签管理
创建标签
# 轻量标签
git tag v1.0.0
git tag v1.0.0 commit-hash
# 附注标签(推荐)
git tag -a v1.0.0 -m "Version 1.0.0 release"
git tag -a v1.0.0 commit-hash -m "Version 1.0.0"
# 签名标签(需要GPG)
git tag -s v1.0.0 -m "Signed version 1.0.0"
# 查看标签
git tag
git tag -l "v1.*" # 模式匹配
git show v1.0.0 # 查看标签详情
推送标签
# 推送单个标签
git push origin v1.0.0
# 推送所有标签
git push origin --tags
# 删除标签
git tag -d v1.0.0 # 删除本地标签
git push origin --delete v1.0.0 # 删除远程标签
git push origin :refs/tags/v1.0.0 # 同上
储藏操作
基础储藏
# 储藏当前修改
git stash
git stash push -m "Work in progress"
# 查看储藏列表
git stash list
# 应用储藏
git stash apply # 应用最新储藏
git stash apply stash@{2} # 应用指定储藏
git stash pop # 应用并删除储藏
# 删除储藏
git stash drop # 删除最新储藏
git stash drop stash@{2} # 删除指定储藏
git stash clear # 清空所有储藏
# 查看储藏内容
git stash show
git stash show -p # 显示具体变更
git stash show stash@{2} -p
高级储藏操作
# 储藏包含未跟踪文件
git stash -u
git stash --include-untracked
# 储藏所有修改(包括忽略文件)
git stash -a
git stash --all
# 从储藏创建分支
git stash branch new-branch stash@{1}
# 应用储藏的特定文件
git checkout stash@{0} -- file.txt
git show stash@{0}:file.txt > file.txt
子模块管理
添加子模块
# 添加子模块
git submodule add https://github.com/user/repo.git
git submodule add https://github.com/user/repo.git path/to/submodule
# 克隆包含子模块的项目
git clone --recursive https://github.com/user/repo.git
# 在已有项目中初始化子模块
git submodule init
git submodule update
git submodule update --init --recursive
子模块操作
# 更新子模块
git submodule update
git submodule update --remote # 更新到远程最新
# 查看子模块状态
git submodule status
git submodule summary
# 进入子模块目录
cd path/to/submodule
git checkout main # 在子模块中操作
cd ../.. # 返回主项目
# 提交子模块更新
git add path/to/submodule
git commit -m "Update submodule"
# 删除子模块
git submodule deinit path/to/submodule
git rm path/to/submodule
git rm -r --cached path/to/submodule
rm -rf .git/modules/path/to/submodule
工作流示例
Git Flow 工作流
# 初始化Git Flow
git flow init
# 创建功能分支
git flow feature start new-feature
# 开发功能...
git flow feature finish new-feature
# 创建发布分支
git flow release start v1.0.0
# 修复发布问题...
git flow release finish v1.0.0
# 创建热修复分支
git flow hotfix start fix-bug
# 修复紧急问题...
git flow hotfix finish fix-bug
GitHub Flow 工作流
# 1. 从main创建功能分支
git checkout main
git pull origin main
git checkout -b feature/new-feature
# 2. 开发并提交
git add .
git commit -m "Add new feature"
# 3. 推送到远程
git push origin feature/new-feature
# 4. 创建Pull Request
# 在GitHub网页上操作
# 5. 代码审查后合并到main
git checkout main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature
GitLab Flow 工作流
# 1. 创建功能分支
git checkout -b feature/user-authentication
# 2. 开发并提交
git add .
git commit -m "Implement user authentication"
# 3. 推送到远程
git push origin feature/user-authentication
# 4. 创建Merge Request到develop分支
git checkout develop
git pull origin develop
git merge feature/user-authentication
git push origin develop
# 5. 从develop创建发布分支
git checkout -b release/v1.0.0 develop
git push origin release/v1.0.0
# 6. 发布后合并到main
git checkout main
git merge release/v1.0.0
git tag v1.0.0
git push origin main --tags
高级技巧
交互式变基示例
# 清理提交历史
git rebase -i HEAD~5
# 编辑提交信息(reword)
r 1234567 Fix typo in README
# 合并提交(squash)
s 2345678 Add feature A
s 3456789 Add feature B
# 删除提交(drop)
d 4567890 Remove debug code
# 重新排序提交
# 在编辑器中重新排列提交顺序
Cherry-pick 操作
# 选择特定提交到当前分支
git cherry-pick commit-hash
# 选择多个提交
git cherry-pick commit1..commit3
# 不自动提交
git cherry-pick --no-commit commit-hash
# 解决冲突后继续
git cherry-pick --continue
# 中断cherry-pick
git cherry-pick --abort
Bisect 调试
# 开始二分查找
git bisect start
# 标记已知状态
git bisect bad HEAD # 当前版本有问题
git bisect good v1.0.0 # v1.0.0版本正常
# 自动二分查找
git bisect run make test # 运行测试脚本
# 手动检查
git bisect good # 当前版本正常
git bisect bad # 当前版本有问题
# 结束二分查找
git bisect reset
配置文件
全局配置文件
# ~/.gitconfig
[user]
name = Your Name
email = your.email@example.com
signingkey = ABC12345
[core]
editor = code --wait
autocrlf = input
filemode = false
ignorecase = false
[alias]
st = status
co = checkout
br = branch
ci = commit
lg = log --oneline --graph --decorate
unstage = reset HEAD --
last = log -1 HEAD
visual = !gitk
[push]
default = simple
[pull]
rebase = true
[merge]
tool = vscode
[diff]
tool = vscode
项目配置文件
# .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
[remote "origin"]
url = https://github.com/user/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
merge = refs/heads/main
[alias]
deploy = !git push origin main && git push origin --tags
忽略文件
# .gitignore
# 操作系统文件
.DS_Store
Thumbs.db
*.swp
*.swo
# IDE文件
.vscode/
.idea/
*.sublime-*
# 依赖目录
node_modules/
vendor/
target/
# 构建产物
*.log
*.tmp
dist/
build/
# 环境配置
.env
.env.local
.env.*.local
# 临时文件
*.pid
*.seed
*.pid.lock
# 测试覆盖率
coverage/
.nyc_output/
# 缓存
.cache/
.parcel-cache/
常见问题解决
合并冲突解决
# 查看冲突文件
git status
# 手动编辑冲突文件
# <<<<<<< HEAD
# 当前分支的内容
# =======
# 合并分支的内容
# >>>>>>> feature-branch
# 解决冲突后添加文件
git add conflicted-file.txt
# 继续合并
git merge --continue
# 放弃合并
git merge --abort
恢复丢失的提交
# 查看所有操作记录
git reflog
# 恢复丢失的提交
git checkout commit-hash
git checkout -b recovery-branch commit-hash
# 恢复到特定状态
git reset --hard HEAD@{5}
清理仓库
# 清理未跟踪文件
git clean -fd
git clean -nfd # 预览
# 清理无用分支
git branch -d $(git branch --merged | grep -v main)
git remote prune origin # 清理远程分支引用
# 垃圾回收
git gc
git gc --aggressive # 更彻底的清理
性能优化
大文件处理
# 使用Git LFS
git lfs install
git lfs track "*.zip"
git lfs track "*.pdf"
git add .gitattributes
git add large-file.zip
git commit -m "Add large file with LFS"
# 查找大文件
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort --numeric-sort --key=2 | tail -10
浅克隆优化
# 浅克隆(只获取最新提交)
git clone --depth 1 https://github.com/user/repo.git
# 单分支克隆
git clone --single-branch https://github.com/user/repo.git
# 指定分支浅克隆
git clone --depth 1 --branch main https://github.com/user/repo.git
总结
Git是一个功能强大的版本控制系统,掌握其基本操作和高级技巧可以大大提高开发效率。在实际使用中,建议根据项目需求选择合适的工作流,并养成良好的提交习惯。定期备份重要分支,合理使用分支策略,保持仓库整洁,这些都是高效使用Git的关键。
💬 评论