Git 常用命令汇总

导言

如果你是新手小白,完全不懂git,可以先看这一篇 github 详细教程

本文仅适用于对 git 操作已经有了一定掌握的用户,本文的目的在于将常用命令统一梳理记录,便于查阅。


干货

  • 克隆指定分支:git clone -b <branch_name> <git_repo_link>
  • git add的反操作:git reset HEAD [文件名, optional]
  • git commit的反操作:
    • 恢复到暂存区: git reset --soft HEAD^
    • 直接丢弃commit的修改:git reset --hard HEAD^
  • 本地覆盖远程:git push origin -f
  • 远程覆盖本地:git reset --hard origin/master && git pull
  • 拉取所有更新(但不同步):git fetch --all
  • 分支(branch):
    • 创建分支:git checkout -b <new_branch> [old_branch, optional,默认是当前分支]
    • 删除分支:git branch -d(or -D,强制删除) <branch_name>
    • 删除远程分支:git push --delete origin <branch_name>
    • 修改分支名:git branch -m <old_name> <new_name>
  • 标签(tag,tag其实也是一个 branch):
    • 创建 tag:git tag <tag_name>
    • 查看 tag 列表:git tag
    • 查看 tag 列表(有过滤条件):git tag -l "0.1.0*" (只查看0.1.0开头的tag)
    • 删除 tag:git tag -d <tag_name>
    • 将 tag 同步到远程:git push origin <tag_name>
  • git stash相关:
    • 将修改暂存:git stash
    • 将修改释放:git stash pop
    • 查看暂存的修改:git stash list
  • git merge & git rebase 相关,假定我们现在在一个从master checkout 出来的 feature 分支上,(https://joyohub.com/2020/04/06/git-rebase/):
    • git merge master:会在feature 分支的顶端新建个merge commit,将两个分支的修改merge在一起
      • 优点:非破坏性
      • 缺点:创建了新的merge 节点,会使feature分支的历史记录变的复杂,尤其是如果master更新频繁的话,会把feature的提交记录搞的很脏
    • 只merge特定的几个commit(cherry pick):
      • 只将master里的某个commit 合到 feature 里面来:git cherry-pick <commit_id of master>
      • 将master里的某一段commit合到 feature 里面来:git cherry-pick <start_commit_id>...<end_commit_id> (左开右闭,不包含start_commit_id
    • git rebase master:将 feature分支的改动移动到master分支的顶端,不会创建新commit
      • 优点:项目历史很清晰,消除了git merge 所需的不必要的合并节点
      • 缺点:虽然提交历史记录"看起来"是干净整洁的,其实可能会有合并错的风险
    • git rebase 合并多次提交记录:
      • git rebase -i HEAD~4, 进入vi编辑模式;
      • 在编辑模式里修改哪些commit需要被合并,哪些需要保留(pick:保留;squash:和前一个commit合并;drop:删除该commit)
    • git merge 和 git rebase 过程中的 incoming和current branch 分别是什么?
      • git merge:Merge the incoming changes into the current branch
      • git rebase:Rebase the current branch on top of the incoming changes
相关推荐
徐小夕2 小时前
我们用1万行Vue3代码,做了款开源AI PPT项目
github
苏同学4 小时前
LangGraph 实战:从零实现多工具协作的可追溯文档问答 Agent
github
逛逛GitHub5 小时前
给 OpenClaw 小龙虾🦞搞个像素办公室,这个 GitHub 项目有趣啊。
github
doup智能AI9 小时前
数据分析师:报表自动生成与洞察——AI 员工系列 Vol.4
github
今日无bug9 小时前
Git 提交:用全栈技术打造智能 Commit Message 生成器
git·全栈
答案answer9 小时前
Three.js3D编辑器必备的相机视图插件
开源·github·three.js
明月_清风11 小时前
拒绝盲目 Git:VS Code 神级插件 GitLens 的 9 个进效杀手锏
前端·git
RickeyBoy19 小时前
Git Worktree / Worktrunk:并行 AI 开发工作流实战
github·vibecoding
逛逛GitHub1 天前
55 个 AI Agent 组成虚拟公司开源,2 天就 1 万星
github
Tapir1 天前
被 Karpathy 下场推荐的 NanoClaw 是什么来头
前端·后端·github