当前位置: 首页 > news >正文

Git 命令指南:从 0 到熟练、从常用到“几乎全集”(含常见报错与解决)建议收藏!!!

Git 命令指南:从 0 到熟练、从常用到“几乎全集”(含常见报错与解决)

写在前面:Git 的命令分为瓷器(Porcelain)管道(Plumbing)两类。日常开发主要用瓷器;运维/排障时会碰到若干管道命令。本文先给高频 20 条,再按类别梳理几乎所有常见命令及作用,并附错误排查速查表。你可以把本文当作 Cheat Sheet + 故障手册

文章目录

  • Git 命令指南:从 0 到熟练、从常用到“几乎全集”(含常见报错与解决)
    • @[toc]
    • 1)五分钟上手(最常用 20 条)
    • 2)命令详解(瓷器 Porcelain)
      • 2.1 仓库与配置
      • 2.2 快照与索引
      • 2.3 查看与比较
      • 2.4 分支与合并
      • 2.5 远端协作
      • 2.6 清理与维护
    • 3)常用管道(Plumbing)命令(排障必备)
    • 4)典型工作流“菜谱”
      • 4.1 开新功能分支 → 提交 → Rebase → 推 PR
      • 4.2 修正上一提交(不改 SHA 或改 SHA)
      • 4.3 回滚线上问题(公共分支)
      • 4.4 只拿某个修复到当前分支
      • 4.5 暂存现场切分支修 bug
    • 5)命令一览(分类“几乎全集”索引 + 作用)
      • 获取与创建(Getting and Creating Repositories)
      • 快照(Snapshotting)
      • 分支与合并(Branching & Merging)
      • 共享与更新(Sharing & Updating)
      • 查看与比较(Inspection & Comparison)
      • 补丁与邮件(Patching / Email)
      • 维护与管理(Administration / Maintenance)
      • 常用管道(Plumbing)选摘
    • 6)常见报错 & 解决(速查表)
    • 7)Reset / Restore / Checkout 怎么选?
    • 8)推荐配置(一次到位)
    • 9)附:常见场景脚本与截图建议
    • 10)结语

1)五分钟上手(最常用 20 条)

# 初始化 / 克隆
git init                     # 在当前目录创建仓库
git clone <url>              # 克隆远端仓库# 快照(工作区 -> 暂存区 -> 提交)
git status                   # 查看状态
git add <file/dir>           # 加入暂存区
git restore --staged <f>     # 从暂存区撤回
git commit -m "msg"          # 提交
git commit --amend           # 修改上一条提交# 比对与查看
git diff                     # 工作区 vs 暂存区
git diff --staged            # 暂存区 vs HEAD
git log --oneline --graph    # 历史图
git show <commit>            # 看某个提交/对象# 分支与合并
git branch                   # 列分支
git switch -c feat/x         # 新建并切换
git merge <branch>           # 合并
git rebase <branch>          # 变基(线性历史)# 远端协作
git remote -v                # 远端列表
git fetch                    # 拉取但不合并
git pull                     # fetch + 合并/变基
git push -u origin main      # 推送并建立上游# 回滚与恢复
git revert <commit>          # 生成反向提交(推荐)
git reset --hard <commit>    # **危险** 回到某快照
git stash push -m "wip"      # 暂存工作区
git stash pop                # 取出

2)命令详解(瓷器 Porcelain)

2.1 仓库与配置

  • git init:初始化仓库;-b main 指定默认分支名。
  • git clone <url> [dir]:克隆;--depth N 浅克隆。
  • git config [--global] key value:配置;常用:
    • user.name / user.email 身份;
    • init.defaultBranch main 默认分支名;
    • core.autocrlf input|true|false 行尾;
    • pull.rebase true|false|merges 拉取策略;
    • alias.xxx '命令' 自定义别名。

2.2 快照与索引

  • git status:状态。
  • git add:把工作区更改放到暂存区-p 交互式分块。
  • git restore [--staged] <f>:撤销(工作区/暂存区)。
  • git rm [-r] <path>:删除并记录到暂存区;--cached 只从索引移除。
  • git mv <a> <b>:重命名(等价于 add+rm)。
  • git commit [-m]:提交;--amend 修改上一提交;--no-verify 跳过钩子。
  • git tag [v1.0]:打标签;-a 附注;-d 删除;push --tags 推送。

2.3 查看与比较

  • git log [--oneline --graph --decorate]:历史。
  • git show <obj>:查看提交/标签/文件某版本。
  • git diffgit diff --staged:差异;--name-only 只看文件名;<A>..<B> 比两点。
  • git blame <f>:逐行追溯。
  • git grep <pattern>:搜索内容。
  • git describe:用最近标签描述提交。

2.4 分支与合并

  • git branch:本地分支;-r 远端;-a 全部。
  • git switch <b> / git checkout <b>:切换;-c 新建。
  • git merge <b>:把 <b> 合并到当前分支;冲突后 git add 解决再 commit
  • git rebase <b>:把当前分支的提交搬到 <b> 之上;-i 交互式整理(squash / fixup)。
  • git cherry-pick <commit..>:拣选一或多提交。
  • git revert <commit>:生成“反向提交”,推荐用于公共分支
  • git worktree:多工作树并行开发。

2.5 远端协作

  • git remote add origin <url>:添加远端。
  • git fetch [origin] [refspec]:拉取;--prune 清理远端已删分支。
  • git pull:fetch+合并/变基;推荐明确:git pull --rebase 或配置 pull.rebase=true
  • git push [--set-upstream] origin <branch>:推送并设置上游;--force-with-lease 安全强推。
  • git submodule:子模块;git submodule update --init --recursive 初始化更新。
  • git sparse-checkout:稀疏检出(只要子目录)。

2.6 清理与维护

  • git clean -fdx:清理未跟踪文件(谨慎);
  • git gc:垃圾回收;git fsck 完整性检查;
  • git reflog:引用日志(救命神器,找回误删)。
  • git bisect:二分定位问题提交。
  • git range-diff:比较两段提交的差异(PR 变基后对比好用)。
  • git shortlog:提交统计。

3)常用管道(Plumbing)命令(排障必备)

这些命令更底层,名字略“生硬”,但排障/脚本化时非常有用。

  • 对象与树

    • git cat-file -t|-p <obj>:查看对象类型/内容。
    • git ls-tree <commit> [path]:列出树对象。
    • git write-tree / git read-tree:读写索引与树对象。
    • git hash-object -w <file>:把文件写入对象库。
  • 引用与提交图

    • git rev-parse:解析引用(如 HEAD~3)。
    • git rev-list <range>:列出提交序列。
    • git show-ref:列出引用(分支/标签)。
    • git update-ref:直接改引用值(危险)。
  • 索引与路径

    • git ls-files:索引中文件。
    • git check-ignore -v <path>:为什么被 .gitignore 忽略。
    • git update-index:直接操作索引(缓存)。
  • 补丁/导入导出

    • git apply:应用补丁(工作区/索引);
    • git format-patch / git am:导出/导入邮件补丁流。
    • git bundle:打包仓库为单文件(带历史)。
    • git fast-export / git fast-import:高速迁移。
  • 维护

    • git repack / git prune / git gc:对象整理与清理。
    • git verify-commit / verify-tag / verify-pack:校验签名/包。
    • git maintenance start|run:后台维护任务(8.0+)。

历史命令(不再推荐):git filter-branch(改历史,慢且危险)。现代做法请用 git filter-repo(外部工具)。


4)典型工作流“菜谱”

4.1 开新功能分支 → 提交 → Rebase → 推 PR

git switch -c feat/api
# ...修改...
git add -A && git commit -m "feat: api"
git fetch origin main
git rebase origin/main          # 线性历史
git push -u origin feat/api

4.2 修正上一提交(不改 SHA 或改 SHA)

git commit --amend --no-edit    # 只补文件,不改提交信息(会改 SHA)
# 若公共分支已共享,谨慎:git push --force-with-lease

4.3 回滚线上问题(公共分支)

git revert <bad-commit>         # 生成反向提交,不改历史
git push

4.4 只拿某个修复到当前分支

git cherry-pick <fix-commit>

4.5 暂存现场切分支修 bug

git stash push -m "wip"
git switch -c hotfix/x
# 修复...
git switch -
git stash pop

5)命令一览(分类“几乎全集”索引 + 作用)

下面按 git help -a 的常见分组给出名称 + 一句作用粗体为高频):

获取与创建(Getting and Creating Repositories)

  • init 初始化仓库
  • clone 克隆仓库
  • config 配置
  • help 帮助
  • worktree 多工作树

快照(Snapshotting)

  • add 加入暂存区
  • status 状态
  • diff 差异
  • commit 创建提交
  • reset 回到某状态(移动 HEAD/索引/工作区)
  • rm/mv/restore 删除/移动/恢复
  • stash 暂存现场
  • tag 标签
  • bisect 二分定位

分支与合并(Branching & Merging)

  • branch 分支管理
  • switch/checkout 切换
  • merge 合并
  • rebase 变基
  • cherry-pick 拣选
  • revert 反向提交
  • range-diff 比较两段提交差异
  • worktree 并行工作树

共享与更新(Sharing & Updating)

  • remote 管理远端
  • fetch 拉取不合并
  • pull 拉取并合并/变基
  • push 推送
  • submodule 子模块
  • sparse-checkout 稀疏检出
  • bundle 打包传输

查看与比较(Inspection & Comparison)

  • log 历史
  • show 查看对象
  • grep 搜索
  • blame 逐行追溯
  • shortlog 统计
  • reflog 引用日志
  • describe 标签描述

补丁与邮件(Patching / Email)

  • format-patch / am 导出/应用补丁
  • apply 应用 patch
  • send-email(可选组件) 发送补丁

维护与管理(Administration / Maintenance)

  • gc 垃圾回收
  • fsck 完整性检查
  • repack/prune 重打包/清理
  • verify-commit/tag/pack 验证
  • update-server-info 无智能服务的 HTTP 支持
  • filter-branch(历史)历史重写(不推荐)
  • maintenance 后台维护任务

常用管道(Plumbing)选摘

  • cat-file / ls-tree / ls-files 查看对象/树/索引
  • hash-object / write-tree / read-tree 操作对象/树
  • rev-parse / rev-list / show-ref / update-ref 解析与管理引用
  • check-ignore / check-attr 忽略与属性检查
  • pack-objects / index-pack / verify-pack 包操作
  • fast-export / fast-import 迁移
  • symbolic-ref 设置/读取符号引用(如 HEAD)

说明:Git 官方共有上百条命令,以上已覆盖日常开发与绝大多数排障所需。如需逐条 man page,请在本地运行 git help -a / git help <cmd>


6)常见报错 & 解决(速查表)

报错/症状原因解决
fatal: not a git repository不在仓库内/子目录丢失 .gitcd 到仓库;或确认 .git 未被删
fatal: remote origin already exists重复添加远端git remote set-url origin <url>git remote remove origin
error: failed to push some refs / non-fast-forward远端有你本地没有的提交git pull --rebase 后再 git push;或用 --force-with-lease
Updates were rejected because the remote contains work...同上同上,优先用 rebase 合并远端
refusing to merge unrelated histories两端历史无共同祖先git pull --allow-unrelated-histories(仅一次性合并)
detached HEAD处在游离 HEAD(检出到提交)git switch -c tmp 建分支保存,或 git switch <branch>
合并冲突 <<<<<<<两边同时修改手动解决后 git add + git commit;或 git merge --abort
Permission denied (publickey)SSH Key 未配置生成并添加公钥;或改用 HTTPS
SSL certificate problem证书问题配置受信 CA 或改用 SSH(不建议全局禁用验证)
LF will be replaced by CRLF行尾转换提示设置 git config core.autocrlf input(mac/linux)或 true(windows)
filename too long(Windows)路径过长管理员打开 git config --system core.longpaths true
index.lock 存在上次异常中断确认无 git 进程后删除 .git/index.lock
fatal: bad object <sha> / 对象损坏仓库损坏/中断git fsck,必要时 git gc --prune=now 或重新克隆
RPC failed; curl 56 / 推送大文件失败大文件/网络问题走 Git LFS:git lfs install && git lfs track;检查代理/网络
Your branch is behind本地落后git pull --rebase
fatal: The current branch has no upstream branch未设上游git push -u origin <branch>
shallow update not allowed浅克隆限制git fetch --unshallow 或全量克隆

救援三板斧

  1. git reflog 找回引用移动历史;
  2. git fsck 检查对象库;
  3. 新克隆一份 与本地比对,必要时 cherry-pick 搬迁。

7)Reset / Restore / Checkout 怎么选?

  • git restore <file>:把工作区文件还原为索引或指定提交。
  • git restore --staged <file>:把暂存区还原为 HEAD。
  • git reset --soft|--mixed|--hard <commit>:移动 HEAD(及索引/工作区)。
    • --soft 只动 HEAD;--mixed(默认)动 HEAD+索引;--hard 三者都回退(危险)。
  • git switch:专注切分支;git checkout 兼顾检出文件/分支(老习惯)。

8)推荐配置(一次到位)

git config --global user.name  "你的名字"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global pull.rebase false        # 或 true,团队统一即可
git config --global core.autocrlf input      # mac/linux; windows 可 true
git config --global fetch.prune true
git config --global alias.lg "log --oneline --graph --decorate --all"

9)附:常见场景脚本与截图建议

  • DDL/造数不适用 Git,但你可以准备一个“示例仓库”用于截图:
    1. 制造冲突并演示解决;
    2. EXPLAIN 不适用,改用 git log --graph/range-diff 展示 rebase 前后;
    3. “慢查截图”换成 慢推送/大文件报错 的复现终端截图。
  • 若要做团队规范,附上 .gitignore 模板、pre-commit 钩子示例(如 lint、secret 扫描)。

10)结语

Git 不止会用 add/commit/push。把条件 rebase、cherry-pick、revert、reflog、bisect 这些“王牌”掌握后,你基本能从容处理 90% 的协作与故障。本文把高频操作、几乎全量命令目录、以及常见错误与解法都放到了一处,建议收藏为团队的随手册

http://www.lryc.cn/news/623475.html

相关文章:

  • LintCode第137-克隆图
  • 学习游戏制作记录(玩家掉落系统,删除物品功能和独特物品)8.17
  • 《设计模式》工厂方法模式
  • 代码随想录算法训练营四十四天|图论part02
  • 天地图开发的优点
  • The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
  • GANs生成对抗网络生成手写数字的Pytorch实现
  • VS Code配置MinGW64编译Apache Arrow C++库
  • 【k8s、docker】Headless Service(无头服务)
  • python+flask后端开发~项目实战 | 博客问答项目--模块化文件架构的基础搭建
  • C++算法题目分享:二叉搜索树相关的习题
  • 【前端基础】flex布局中使用`justify-content`后,最后一行的布局问题
  • ubuntu 24.04 安装
  • Android RxJava线程调度与性能优化指南
  • (一)前端面试(cookie/)
  • PostgreSQL导入mimic4
  • 数据结构代码分享-1 顺序表
  • 简单的 VSCode 设置
  • Oracle algorithm的含义
  • 基于Vue + Node能源采购系统的设计与实现/基于express的能源管理系统#node.js
  • Qt 5.5 的安装与配置(使用 VSCode编辑)
  • 【架构师从入门到进阶】第五章:DNSCDN网关优化思路——第十二节:网关安全-信息过滤
  • 基于多Agent的AFSIM复杂场景脚本生成技术(使用Claude Code)
  • 根号算法Ⅰ
  • 天地图应用篇: 增加缩放、比例尺控件
  • 24. 什么是不可变对象,好处是什么
  • 【Docker】搭建一款功能强大且免费的开源在线绘图工具 - draw.io
  • 云原生俱乐部-RH134知识点总结(2)
  • 62.不同路径
  • 【计算机网络面试】键入网址到网页显示期间,发生了什么?