Git命令大全:从入门到精通

Git命令详解

Git是目前最流行的分布式版本控制系统,广泛应用于软件开发领域。本文将详细介绍Git的常用命令,帮助你从入门到精通。

常用命令速查表

以下是Git最常用的命令,按功能分类,方便快速查阅:

仓库操作

命令 描述
git init 初始化新仓库
git clone url 克隆远程仓库
git clone url --depth 1 浅克隆(只获取最新提交)

文件操作

命令 描述
git add file 添加文件到暂存区
git add -A 添加所有修改
git commit -m "msg" 提交
git commit --amend 修改最后一次提交
git status 查看状态
git restore file 恢复文件

分支操作

命令 描述
git branch 查看分支
git branch name 创建分支
git checkout name 切换分支
git checkout -b name 创建并切换
git branch -d name 删除分支
git merge name 合并分支

远程操作

命令 描述
git fetch 获取远程更新
git pull 拉取并合并
git push 推送到远程
git push -u origin main 推送并设置上游
git remote -v 查看远程仓库

查看历史

命令 描述
git log 查看提交历史
git log --oneline 简洁格式
git log -p file 查看文件历史
git diff 查看差异
git blame file 查看文件修改记录

撤销操作

命令 描述
git reset --soft HEAD~1 软回滚(保留修改)
git reset --hard HEAD~1 硬回滚(丢弃修改)
git revert commit 还原提交
git stash 暂存工作

进阶操作

命令 描述
git rebase main 变基到主分支
git rebase -i HEAD~n 交互式变基
git cherry-pick commit 拣选提交
git tag 管理标签
git bisect 二分查找bug

实用技巧

命令 描述
git remote update origin --prune 更新并清理远程分支
`git branch --merged grep -v '*'
git log @{u}.. 查看未推送提交
git config --global alias.xxx "cmd" 设置别名

1. Git基础配置

1.1 配置用户信息

在开始使用Git之前,首先需要配置用户信息,这些信息将作为每次提交的作者标识。

bash 复制代码
# 配置全局用户名
git config --global user.name "Your Name"

# 配置全局邮箱
git config --global user.email "your.email@example.com"

# 配置编辑器
git config --global core.editor vim

# 配置默认分支名
git config --global init.defaultBranch main

1.2 查看配置

bash 复制代码
# 查看所有配置
git config --list

# 查看某个配置项
git config user.name
git config --global --list

# 查看配置的来源文件
git config --list --show-origin

1.3 配置文件层级

Git的配置分为三个层级:

  • 系统级 (/etc/gitconfig): 对所有用户生效
  • 全局级 (~/.gitconfig): 对当前用户生效
  • 仓库级 (.git/config): 仅对当前仓库生效
bash 复制代码
# 系统级配置
git config --system core.editor vim

# 全局级配置
git config --global user.name "Your Name"

# 仓库级配置
git config user.name "Project Name"

2. 仓库操作

2.1 初始化仓库

bash 复制代码
# 在当前目录初始化Git仓库
git init

# 初始化仓库并指定目录名
git init my-project

# 初始化一个裸仓库(用于共享)
git init --bare my-repo.git

git init 会创建 .git 目录,这是Git的核心仓库结构:

复制代码
.git/
├── HEAD          # 指向当前分支
├── config        # 仓库配置
├── hooks/        # 钩子脚本
├── objects/      # 所有数据对象
├── refs/         # 引用(分支、标签)
└── index         # 暂存区索引

2.2 克隆仓库

bash 复制代码
# HTTPS方式克隆
git clone https://github.com/user/repo.git

# SSH方式克隆
git clone git@github.com:user/repo.git

# 克隆并指定目录名
git clone https://github.com/user/repo.git my-folder

# 克隆特定分支
git clone -b branch-name 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

3. 文件操作

3.1 添加文件到暂存区

bash 复制代码
# 添加特定文件
git add file.txt

# 添加多个文件
git add file1.txt file2.txt

# 添加目录下所有文件
git add directory/

# 添加所有修改(包括新文件、修改、删除)
git add -A
git add --all

# 添加修改和删除,但不包括新文件
git add -u
git add --update

# 交互式添加
git add -i
git add --interactive

# 查看将要添加的内容
git add -n
git add --dry-run

3.2 从工作区和暂存区删除文件

bash 复制代码
# 从工作区和暂存区删除文件
git rm file.txt

# 只从暂存区删除(保留工作区文件)
git rm --cached file.txt

# 删除目录下所有已跟踪文件
git rm '*.log'

# 强制删除(用于被修改过的文件)
git rm -f file.txt

# 递归删除目录
git rm -r directory/

3.3 移动/重命名文件

bash 复制代码
# 重命名文件
git mv old-name.txt new-name.txt

# 移动文件到目录
git mv file.txt directory/

# 移动并重命名
git mv old.txt directory/new.txt

3.4 查看文件状态

bash 复制代码
# 查看工作区和暂存区状态
git status

# 简洁格式输出
git status -s
git status --short

# 显示分支信息
git status -b
git status --branch

# 忽略已忽略的文件
git status --porcelain

3.5 恢复文件

bash 复制代码
# 从暂存区恢复文件到工作区(丢弃工作区修改)
git restore file.txt

# 从最新提交恢复文件
git restore --source=HEAD file.txt

# 从指定提交恢复文件
git restore --source=commit-hash file.txt

# 恢复所有修改的文件
git restore .

# 恢复被删除的文件
git restore --staged file.txt
git restore file.txt

4. 提交操作

4.1 创建提交

bash 复制代码
# 提交暂存区的内容
git commit -m "Commit message"

# 提交并编辑提交信息
git commit

# 将工作区直接提交(跳过暂存区)
git commit -a -m "Commit message"

# 修改最后一次提交
git commit --amend

# 修改最后一次提交并编辑信息
git commit --amend -m "New message"

# 修改最后一次提交但保持原信息
git commit --amend --no-edit

# 修改最后一次提交的作者
git commit --amend --author="New Author <email@example.com>"

# 指定日期提交
GIT_AUTHOR_DATE="2024-01-01T10:00:00" git commit -m "Backport commit"

# 签署提交
git commit -S -m "Signed commit"

4.2 提交消息规范

复制代码
<type>(<scope>): <subject>

<body>

<footer>

Type类型:

  • feat: 新功能
  • fix: 修复bug
  • docs: 文档更新
  • style: 代码格式(不影响功能)
  • refactor: 重构
  • perf: 性能优化
  • test: 测试
  • chore: 构建过程或辅助工具

5. 查看历史

5.1 查看提交日志

bash 复制代码
# 查看完整提交历史
git log

# 每行显示一个提交
git log --oneline

# 显示更紧凑的历史
git log --oneline --graph

# 显示前N条记录
git log -5
git log --max-count=5

# 显示提交统计信息
git log --stat

# 显示文件差异
git log -p
git log --patch

# 按关键字搜索
git log --grep="keyword"

# 按文件搜索
git log --follow file.txt

# 按作者搜索
git log --author="authorname"

# 时间范围筛选
git log --since="2024-01-01"
git log --until="2024-12-31"
git log --since="2 weeks ago"

# 显示分支合并图
git log --all --graph --decorate --oneline

# 显示reflog引用记录
git log -g

5.2 查看差异

bash 复制代码
# 工作区与暂存区差异
git diff

# 暂存区与最新提交差异
git diff --cached
git diff --staged

# 工作区与指定提交差异
git diff commit-hash

# 两个提交之间的差异
git diff commit1-hash commit2-hash

# 只显示文件名
git diff --name-only

# 显示统计信息
git diff --stat

# 比较分支
git diff main..feature

# 比较单个文件
git diff file.txt

5.3 查看文件历史

bash 复制代码
# 查看文件的完整历史
git log -p file.txt

# 查看文件的简略历史
git log --oneline file.txt

# 查看是谁最后修改了某行
git blame file.txt

# 查看某范围的blame
git blame -L 10,20 file.txt

# 显示修改者邮箱
git blame -e file.txt

6. 分支操作

6.1 查看分支

bash 复制代码
# 查看所有本地分支
git branch

# 查看所有分支(包括远程)
git branch -a

# 查看远程分支
git branch -r

# 查看已合并到当前分支的分支
git branch --merged

# 查看未合并到当前分支的分支
git branch --no-merged

# 查看分支的最后提交
git branch -v
git branch -vv

# 查看所有分支及其上游
git branch -a -vv

6.2 创建分支

bash 复制代码
# 创建新分支
git branch feature-branch

# 基于指定提交创建分支
git branch feature-branch commit-hash

# 创建并切换到新分支
git checkout -b feature-branch
git switch -c feature-branch

# 基于远程分支创建本地分支
git checkout -b feature-branch origin/feature-branch

# 创建孤儿分支(没有父提交)
git checkout --orphan orphan-branch

6.3 切换分支

bash 复制代码
# 切换到已有分支
git checkout branch-name
git switch branch-name

# 切换到上一个分支
git checkout -
git switch -

# 强制切换(丢弃本地修改)
git checkout -f branch-name
git switch -f branch-name

# 切换并创建(如果分支不存在)
git checkout -b new-branch
git switch -C new-branch

6.4 删除分支

bash 复制代码
# 删除本地分支
git branch -d branch-name

# 强制删除本地分支
git branch -D branch-name

# 删除远程分支
git push origin --delete branch-name
git push origin :branch-name

# 删除已被合并的分支
git branch --merged | xargs git branch -d

# 清理远程已删除的本地分支
git fetch --prune
git remote prune origin

6.5 重命名分支

bash 复制代码
# 重命名当前分支
git branch -m new-name

# 重命名指定分支
git branch -m old-name new-name

# 重命名远程分支(需先删除后推送)
git branch -m old-name new-name
git push origin :old-name new-name
git push origin new-name

6.6 设置上游分支

bash 复制代码
# 设置上游分支
git branch --set-upstream-to=origin/main

# 简写
git branch -u origin/main

# 查看上游分支
git branch -vv

7. 合并操作

7.1 合并分支

bash 复制代码
# 合并分支到当前分支
git merge branch-name

# 创建合并提交(不Fast-forward)
git merge --no-ff branch-name

# 使用squash合并
git merge --squash branch-name

# 只合并特定提交
git merge --no-commit branch-name

# 合并并签署
git merge -S branch-name

# 中止合并
git merge --abort

# 解决冲突后继续合并
git add resolved-file.txt
git commit

7.2 变基(Rebase)

bash 复制代码
# 变基到目标分支
git rebase main

# 交互式变基
git rebase -i HEAD~5

# 从指定位置变基
git rebase --onto new-base current-base feature-branch

# 变基时跳过冲突提交
git rebase --skip

# 中止变基
git rebase --abort

# 继续变基(解决冲突后)
git add resolved-file.txt
git rebase --continue

# 变基时自动解决简单冲突
git rebase -X theirs main
git rebase -X ours main

# 保留合并提交
git rebase --preserve-merges

7.3 交互式变基常用命令

在交互式变基中,可使用以下命令:

复制代码
pick    - 保留该提交
reword  - 保留该提交但修改提交信息
edit    - 暂停以便修改该提交
squash  - 与上一个提交合并
fixup   - 与上一个提交合并,丢弃该提交信息
drop    - 删除该提交
exec    - 执行shell命令

8. 远程操作

8.1 管理远程仓库

bash 复制代码
# 查看远程仓库
git remote -v
git remote --verbose

# 添加远程仓库
git remote add origin https://github.com/user/repo.git

# 重命名远程
git remote rename origin upstream

# 删除远程
git remote remove origin
git remote rm origin

# 修改远程URL
git remote set-url origin https://new-url/repo.git

# 获取远程仓库信息
git remote show origin

# 修剪远程已删除的引用
git remote prune origin

8.2 获取和拉取

bash 复制代码
# 从远程获取更新(不合并)
git fetch origin

# 获取所有远程分支
git fetch --all

# 获取特定分支
git fetch origin branch-name

# 获取并删除远程已删除的分支
git fetch --prune

# 拉取并合并(git fetch + git merge)
git pull
git pull origin main

# 变基方式拉取
git pull --rebase
git pull --rebase=preserve

# 只拉取特定分支
git pull origin branch-name

# 中止pull --rebase
git pull --abort

8.3 推送

bash 复制代码
# 推送到远程
git push origin main

# 推送当前分支并设置上游
git push -u origin main

# 推送所有分支
git push --all

# 推送所有标签
git push --tags

# 强制推送(谨慎使用)
git push --force
git push -f

# 强制推送并检查远程历史
git push --force-with-lease

# 删除远程分支后推送
git push origin :branch-name

# 推送标签
git push origin v1.0.0

# 删除远程标签
git push origin :refs/tags/v1.0.0

9. 撤销操作

9.1 Reset(重置)

bash 复制代码
# 软重置(保留更改在暂存区)
git reset --soft HEAD~1
git reset --soft commit-hash

# 混合重置(保留更改在工作区,默认)
git reset HEAD~1
git reset --mixed HEAD~1
git reset commit-hash

# 硬重置(丢弃所有更改)
git reset --hard HEAD~1
git reset --hard commit-hash

# 回退到指定版本
git reset --hard origin/main

# 重置特定文件
git reset file.txt
git reset --hard file.txt

# 查看重置后的状态
git reset --porcelain

9.2 Revert(还原)

bash 复制代码
# 还原指定提交
git revert commit-hash

# 还原多个提交
git revert commit1-hash commit2-hash

# 还原并编辑提交信息
git revert --edit commit-hash

# 还原但不自动提交
git revert --no-commit commit-hash
git revert -n commit-hash

# 还原合并提交
git revert -m 1 merge-commit-hash

# 还原范围提交
git revert HEAD~5..HEAD

9.3 Checkout(检出)

bash 复制代码
# 检出特定提交
git checkout commit-hash

# 检出文件
git checkout commit-hash -- file.txt

# 放弃工作区修改
git checkout -- file.txt

# 放弃所有修改
git checkout -- .

9.4 Restore(恢复)

bash 复制代码
# 从暂存区恢复文件
git restore --staged file.txt

# 从工作树恢复文件
git restore file.txt

# 从指定提交恢复
git restore --source=commit-hash file.txt

# 恢复所有
git restore .

# 恢复并覆盖未跟踪文件
git restore --worktree --staged file.txt

9.5 清理

bash 复制代码
# 清理未跟踪文件
git clean

# 清理未跟踪文件和目录
git clean -fd

# 清理忽略的文件
git clean -fX

# 清理所有(包括忽略的)
git clean -fx

# 先预览再清理
git clean -n

10. 标签管理

10.1 查看标签

bash 复制代码
# 列出所有标签
git tag

# 列出匹配模式的标签
git tag -l "v1.*"

# 查看标签信息
git show v1.0.0

# 查看标签对应的提交
git rev-parse v1.0.0

10.2 创建标签

bash 复制代码
# 创建轻量标签
git tag v1.0.0

# 创建附注标签
git tag -a v1.0.0 -m "Version 1.0.0"

# 为指定提交创建标签
git tag -a v1.0.0 commit-hash

# 创建带签名的标签
git tag -s v1.0.0 -m "Signed version"

# 创建GPG签名的标签
git tag -u key-id v1.0.0

10.3 删除和修改标签

bash 复制代码
# 删除本地标签
git tag -d v1.0.0

# 删除远程标签
git push origin :refs/tags/v1.0.0
git push origin --delete v1.0.0

# 重命名标签
git tag new-name old-name
git tag -d old-name

# 修改现有标签(先删后建)
git tag -d v1.0.0
git tag -a v1.0.0 -m "Updated message"

10.4 推送标签

bash 复制代码
# 推送指定标签
git push origin v1.0.0

# 推送所有标签
git push --tags

# 推送标签到其他仓库
git push upstream v1.0.0

11. 储藏(Stash)

11.1 基本操作

bash 复制代码
# 储藏当前工作
git stash

# 储藏并添加消息
git stash save "work in progress"

# 储藏未跟踪文件
git stash -u
git stash --include-untracked

# 储藏包含忽略的文件
git stash -a

# 查看储藏列表
git stash list

# 查看储藏内容
git stash show
git stash show -p

# 应用最近储藏
git stash pop

# 应用指定储藏
git stash apply stash@{0}

# 删除最近储藏
git stash drop

# 删除指定储藏
git stash drop stash@{0}

# 清空所有储藏
git stash clear

11.2 分支储藏

bash 复制代码
# 从储藏创建新分支
git stash branch new-branch stash@{0}

# 在新分支上应用储藏
git stash branch new-branch

12. 高级操作

12.1 Cherry-pick

bash 复制代码
# 拣选单个提交
git cherry-pick commit-hash

# 拣选多个提交
git cherry-pick commit1 commit2

# 拣选范围提交
git cherry-pick start-hash..end-hash

# 拣选并编辑
git cherry-pick -n commit-hash
git cherry-pick --no-commit commit-hash

# 拣选时不带提交信息
git cherry-pick --no-commit

# 中止拣选
git cherry-pick --abort

# 解决冲突后继续
git add resolved-file.txt
git cherry-pick --continue

12.2 Bisect(二分查找)

bash 复制代码
# 开始二分查找
git bisect start

# 标记当前版本为bad
git bisect bad

# 标记已知good版本
git bisect good commit-hash

# 标记已知bad版本
git bisect bad commit-hash

# 自动二分查找
git bisect run test-script.sh

# 跳过当前提交
git bisect skip

# 查看当前状态
git bisect status

# 结束二分查找
git bisect reset
git bisect reset HEAD

12.3 子模块

bash 复制代码
# 添加子模块
git submodule add https://github.com/user/repo.git path/to/repo

# 初始化子模块
git submodule init

# 更新子模块
git submodule update

# 更新所有子模块
git submodule update --init --recursive

# 克隆包含子模块的仓库
git clone --recurse-submodules repo-url

# 查看子模块状态
git submodule status

# 移除子模块
git submodule deinit path/to/repo
git rm path/to/repo

12.4 Reflog(引用日志)

bash 复制代码
# 查看引用日志
git reflog

# 查看特定ref的日志
git reflog show HEAD
git reflog refs/heads/main

# 恢复误删的分支
git reflog
git checkout -b branch-name commit-hash

12.5 Grep(搜索)

bash 复制代码
# 在工作区搜索内容
git grep "search term"

# 递归搜索
git grep -r "term"

# 搜索并显示行号
git grep -n "term"

# 搜索并统计
git grep -c "term"

# 搜索特定文件
git grep "term" -- "*.js"

# 搜索忽略的文件
git grep -I "term"

# 搜索提交历史
git log -S "term"

# 搜索提交消息
git log --grep="term"

12.6 归档

bash 复制代码
# 创建压缩归档
git archive -o latest.zip HEAD

# 创建tar归档
git archive --format=tar HEAD | gzip > latest.tar.gz

# 只包含指定路径
git archive -o partial.zip HEAD -- path/to/dir

# 不包含.git目录
git archive -o release.zip HEAD

# 基于标签归档
git archive -o v1.0.0.zip v1.0.0

13. Git别名

13.1 配置别名

bash 复制代码
# 简化常用命令
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.br branch
git config --global alias.last 'log -1 HEAD'

# 高级别名
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.unstage 'reset HEAD --'
git config --global alias.visual '!gitk'

13.2 常用别名推荐

bash 复制代码
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
git config --global alias.df "diff --no-ext-diff"
git config --global alias.dfc "diff --cached --no-ext-diff"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.wip "log --oneline -5"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.cleanup "!git branch --merged | grep -v '\\*\\|main\\|master' | xargs -n 1 git branch -d"

14. Git钩子

14.1 常用钩子

bash 复制代码
# pre-commit: 提交前检查
# .git/hooks/pre-commit

# prepare-commit-msg: 准备提交信息
# .git/hooks/prepare-commit-msg

# commit-msg: 验证提交信息
# .git/hooks/commit-msg

# post-commit: 提交后操作
# .git/hooks/post-commit

# pre-push: 推送前检查
# .git/hooks/pre-push

# pre-receive: 接收前检查(服务端)
# .git/hooks/pre-receive

14.2 安装钩子示例

bash 复制代码
# 安装示例钩子
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit

# 使用husky管理钩子
npx husky install
npx husky add .husky/pre-commit "npm test"

15. GitFlow工作流

15.1 分支模型

复制代码
main/master     ─────────●──●──●──●──●──
                        │     │     │
feature/*        ●──●──●──●     │     │
                        │     │     │
develop          ─●──●──●──●──●──●──●──
                        │  │  │  │
release/*              ●──●──●──●
                        │
hotfix/*            ●──●──●

15.2 GitFlow命令

bash 复制代码
# 初始化GitFlow
git flow init

# 开始新功能
git flow feature start feature-name

# 完成功能
git flow feature finish feature-name

# 发布功能
git flow feature publish feature-name

# 开始发布
git flow release start 1.0.0

# 完成发布
git flow release finish 1.0.0

# 开始热修复
git flow hotfix start hotfix-name

# 完成热修复
git flow hotfix finish hotfix-name

16. 常见问题与解决方案

16.1 合并冲突

bash 复制代码
# 查看冲突文件
git status
git diff --name-only --diff-filter=U

# 查看冲突详情
git diff

# 查看冲突标记
cat file.txt

# 解决冲突后标记为已解决
git add resolved-file.txt

# 使用合并工具
git mergetool

# 中止合并
git merge --abort

16.2 撤销合并

bash 复制代码
# 如果合并还未推送,使用reset
git reset --hard HEAD~1

# 如果合并已推送,使用revert
git revert -m 1 merge-commit-hash

16.3 恢复误删

bash 复制代码
# 恢复误删的文件
git checkout HEAD -- file.txt

# 恢复误删的分支
git reflog
git checkout -b branch-name commit-hash

# 恢复误删的提交
git reflog
git reset --hard commit-hash

16.4 处理大文件

bash 复制代码
# 查找大文件
git rev-list --objects --all | awk '$1 in commitfiles {print}'

# 使用Git LFS
git lfs install
git lfs track "*.zip"
git add .gitattributes
git add large-file.zip

16.5 修改历史

bash 复制代码
# 修改最近几次提交
git rebase -i HEAD~3

# 永久删除敏感信息
git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch path/to/sensitive-file' \
  --prune-empty --tag-name-filter cat -- --all

# 使用BFG清理
bfg --delete-files sensitive-file
bfg --replace-text passwords.txt

17. Git配置示例

17.1 ~/.gitconfig 示例

ini 复制代码
[user]
    name = Your Name
    email = your.email@example.com
[core]
    editor = vim
    whitespace = fix,-indent-with-non-tab,trailing-space,cr-at-eol
    excludesfile = ~/.gitignore_global
[color]
    ui = auto
    branch = auto
    diff = auto
    status = auto
[alias]
    lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    st = status
    co = checkout
    ci = commit
    br = branch
    df = diff --no-ext-diff
    dc = diff --cached --no-ext-diff
    lg1 = log --oneline -5
    unstage = reset HEAD --
    undo = reset --soft HEAD~1
[merge]
    tool = vimdiff
[push]
    default = current
    followTags = true
[pull]
    rebase = true
[init]
    defaultBranch = main
[fetch]
    prune = true
[filter "lfs"]
    clean = git lfs clean %f
    smudge = git lfs smudge %f
    required = true

17.2 .gitignore 示例

复制代码
# 依赖目录
node_modules/
vendor/

# 构建输出
dist/
build/
*.log

# IDE
.idea/
.vscode/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# 环境配置
.env
.env.local
*.local

# 临时文件
*.tmp
*.temp
coverage/
.nyc_output/

18. 性能优化

18.1 优化仓库

bash 复制代码
# 清理无用对象
git gc

# 清理所有不可达对象
git gc --aggressive

# 清理过期的reflog
git reflog expire --expire=now --all

# 清理孤立提交
git prune --expire=now

# 优化并打包
git repack -a -d --depth=250 --window=250

# 检查仓库状态
git fsck

18.2 性能提示

  • 使用浅克隆减少历史记录
  • 使用.gitignore避免提交不必要文件
  • 定期运行git gc清理仓库
  • 避免提交大文件(使用Git LFS)
  • 使用Sparse Checkout仅检出必要文件

19. 最佳实践

  1. 频繁提交: 小步提交,便于回滚和理解历史
  2. 写好提交信息: 清晰描述做了什么和为什么
  3. 使用分支: 功能开发、bug修复都应使用独立分支
  4. 代码审查: 使用Pull Request进行代码审查
  5. 保持同步: 定期从主分支拉取更新
  6. 保护主分支: 设置分支保护规则,防止直接推送
  7. 使用标签: 为发布版本打标签
  8. 备份重要: 定期推送代码到远程仓库

20. 实际使用技巧

20.1 远程仓库管理技巧

bash 复制代码
# 更新远程分支列表并清理已删除的远程分支引用
git remote update origin --prune

# 等效于以下两条命令
git fetch origin
git remote prune origin

# 查看远程分支详细信息
git remote show origin

# 只获取远程分支列表(不下载对象)
git ls-remote origin

# 检查远程仓库是否有更新
git fetch --dry-run origin

# 设置远程仓库多个URL(用于同时推送到多个仓库)
git remote set-url --add origin https://gitee.com/user/repo.git

# 移除某个远程URL
git remote set-url --delete origin https://old-url/repo.git

20.2 分支合并实用技巧

bash 复制代码
# 合并特定文件或目录(从另一个分支)
git checkout feature-branch -- path/to/file.txt
git checkout feature-branch -- directory/

# 合并时排除特定文件或目录
git merge feature-branch -- . ":!file-to-exclude.txt"

# 使用ours策略合并(保留当前分支的版本)
git merge -s ours feature-branch

# 使用theirs策略合并(保留被合并分支的版本)
git merge -s theirs feature-branch

# 只合并某个提交
git cherry-pick commit-hash

# 合并多个提交为一个
git rebase -i HEAD~n
# 将要合并的提交改为 squash 或 fixup

# 将当前分支变基到最新主分支
git fetch origin main
git rebase origin/main
# 或使用 pull 进行变基
git pull --rebase origin main

# 合并并保持线性历史
git merge --ff-only feature-branch
# 只允许快进合并,失败则不合并

# 查看分支差异(合并前)
git diff main..feature-branch
git log main...feature-branch --oneline --left-right

20.3 提交操作技巧

bash 复制代码
# 查看最近的修改内容(未提交)
git diff HEAD

# 查看暂存区和工作区的差异
git diff --staged

# 显示今天的所有提交
git log --since="00:00:00" --until="now"

# 显示某个人的提交统计
git log --author="name" --oneline --stat

# 按提交消息关键词搜索
git log --grep="keyword" --since="1 month ago"

# 查看合并提交
git log --merges

# 查看非合并提交
git log --no-merges

# 显示最近N天的提交
git log --since="N days ago"

# 显示所有分支的共同祖先之后的提交
git log --first-parent

# 格式化输出提交历史
git log --pretty=format:"%h - %s (%an, %ar)"

# 查看某个文件的所有修改者
git log --format="%an" --follow file.txt | sort | uniq

20.4 代码回滚技巧

bash 复制代码
# 撤销最后一次提交(软回滚)
git reset HEAD~1

# 撤销最后一次提交并保留修改
git reset --soft HEAD~1

# 撤销最后一次提交并丢弃修改
git reset --hard HEAD~1

# 撤销某次特定提交
git revert commit-hash

# 撤销某个文件的所有修改
git checkout -- file.txt

# 回退到远程分支状态
git reset --hard origin/main

# 查看可恢复的提交
git reflog
git fsck --lost-found

# 恢复已删除的文件
git restore --source=HEAD~2 --staged --worktree deleted-file.txt

# 撤销最近的N次提交
git revert --no-commit HEAD~N..HEAD
git commit -m "revert last N commits"

20.5 工作区管理技巧

bash 复制代码
# 暂存当前工作并创建新分支
git stash push -m "wip description" -u
git stash branch new-branch-name stash@{0}

# 暂存部分文件
git stash push -m "partial stash" file1.txt file2.txt

# 交互式暂存
git stash push -p -m "interactive stash"
# 然后选择要暂存的内容

# 查看所有分支的工作状态
git worktree list

# 在其他目录创建工作树
git worktree add ../directory-name branch-name

# 删除工作树
git worktree remove ../directory-name

# 保存工作区状态(类似stash,但更持久)
git update-ref -d refs/stash

# 清理工作区中所有未跟踪文件
git clean -fd
# 先预览
git clean -fd -n

20.6 交互式操作技巧

bash 复制代码
# 交互式添加
git add -i
# 或
git add --interactive

# 交互式变基
git rebase -i HEAD~N

# 交互式暂存(部分添加文件)
git add -p
git add --patch
# 选择:
# y - 暂存此块
# n - 不暂存此块
# q - 退出
# a - 暂存此块及之后所有
# d - 不暂存此块及之后所有
# g - 跳转到某个块
# / - 搜索
# s - 分割块
# e - 手动编辑

# 交互式 checkout(部分恢复文件)
git checkout -p file.txt

20.7 调试和分析技巧

bash 复制代码
# 查找引入bug的提交(二分查找)
git bisect start
git bisect bad           # 当前版本有bug
git bisect good v1.0.0   # 好的版本
# Git会自动检出中间版本,测试后标记
git bisect good/bad
# 找到后重置
git bisect reset

# 查找谁修改了某行
git blame -L 10,20 file.txt

# 查找引入某行代码的提交
git log -S "code string" --oneline

# 查找某文件的历史记录
git log --follow -p file.txt

# 查看两个分支之间的差异文件
git diff --name-only main...feature

# 查看某个函数的历史
git log -p -S "function_name()" -- "*.py"

# 检查文件在特定版本是否存在
git ls-tree -r HEAD -- "path/to/file.txt"

# 查看仓库的磁盘使用情况
git count-objects -vH

# 查看最大的对象
git verify-pack -v .git/objects/pack/*.idx | sort -k3 -n | tail -10

20.8 日常开发常用命令组合

bash 复制代码
# 1. 开始新功能开发
git checkout main
git pull origin main
git checkout -b feature/new-feature

# 2. 提交工作进度(下班前)
git add -A
git stash push -m "work in progress: feature X"

# 3. 第二天继续工作
git stash pop

# 4. 功能完成,合并到主分支
git checkout main
git pull origin main
git merge --no-ff feature/new-feature
git push origin main
git branch -d feature/new-feature

# 5. 更新本地所有分支
git fetch --all
for branch in $(git branch -r | grep -v '\->'); do
  git branch --track "${branch#origin/}" "$branch" 2>/dev/null || true
done
git pull --all

# 6. 查看自己今天的改动
git log --author="$(git config user.name)" --since="today" --oneline

# 7. 快速同步远程分支列表
git remote update origin --prune

# 8. 查看未推送到远程的提交
git log @{u}..

# 9. 删除本地已合并到main的分支
git branch --merged main | grep -v '^\*\|main$' | xargs -n 1 git branch -d

# 10. 快速查看改动摘要
git diff --stat

20.9 GitHub/GitLab 特定技巧

bash 复制代码
# 克隆单个文件夹(使用Sparse Checkout)
git init repo
cd repo
git remote add origin https://github.com/user/repo.git
git config core.sparseCheckout true
echo "path/to/folder/" > .git/info/sparse-checkout
git pull origin main

# 查看PR或MR的diff
git fetch origin pull/123/head:pr-123
git diff main..pr-123

# 克隆最新的N个提交
git clone --depth N url

# 浅层更新(增加深度)
git fetch --depth=N origin

# 设置代理
git config --global http.proxy http://proxy:port
git config --global https.proxy https://proxy:port

# 取消代理
git config --global --unset http.proxy
git config --global --unset https.proxy

# 使用SSH代理转发
ssh -A user@jump-server

20.10 提高效率的别名

bash 复制代码
# 设置常用别名
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.df diff
git config --global alias.dc "diff --cached"
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.last "log -1 HEAD"
git config --global alias.unstage "reset HEAD --"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.wip "log --oneline -10 --grep=wip"

# 清理已合并分支的别名
git config --global alias.cleanup '!git branch --merged | grep -v "\\*" | grep -v main | xargs -n 1 git branch -d'

# 查看自己今天的提交
git config --global alias.today '!git log --author="$(git config user.name)" --since="00:00:00" --oneline'

# 快速查看未推送的提交
git config --global alias.unpushed 'log @{u}..HEAD --oneline'

# 查看变更文件列表
git config --global alias.stat 'diff --stat'

# 一键更新并清理
git config --global alias.update '!git fetch --prune && git pull --rebase && git branch --merged | grep -v "\\*" | grep -v main | xargs -n 1 git branch -d 2>/dev/null'

# 查看当前分支与主分支的差异
git config --global alias.diffmain 'diff origin/main...HEAD'

# 强制推送到远程(需确认)
git config --global alias.pushf 'push --force-with-lease'

结语

Git是一个功能强大的版本控制系统,熟练掌握其命令可以大大提高开发效率。建议从基础命令开始,逐步学习高级功能,在实践中不断加深理解。如需更多帮助,请参考官方文档或使用git help命令。

复制代码
git help <command>
git <command> --help
相关推荐
LostSpeed26 分钟前
git - github工程中不能包含大文件
git·github
pzx_00134 分钟前
【GIT】删除远程文件
git
Gofarlic_oms140 分钟前
通过Kisssoft API接口实现许可证管理自动化集成
大数据·运维·人工智能·分布式·架构·自动化
电商API&Tina41 分钟前
电商数据采集 API 接口 全维度解析(技术 + 商业 + 合规)
java·大数据·开发语言·数据库·人工智能·json
小白_ysf1 小时前
Git 命令操作完整指南(实际工作中常用命令)
git·代码上传
雨大王5121 小时前
工业大数据平台:释放数据价值,驱动制造业高质量发展
大数据
瑞华丽PLM1 小时前
破局“多品种、小批量”:瑞华丽 PLM 赋能汽车零部件企业精益研发与智能制造
大数据·汽车·制造·plm·国产plm·瑞华丽plm·瑞华丽
跨境卫士情报站1 小时前
TikTok跨境电商第二增长曲线:从“跑量”到“跑利润”的精细化运营
大数据·人工智能·产品运营·跨境电商·tiktok·营销策略
HealthScience1 小时前
怎么使用git下载huggingface的文件
git
Data-Miner1 小时前
集团数字化转型采购供应链及财务管控业务流程蓝图规划方案(170页PPT)
大数据