git 多分支操作

回到笔记目录

包含 branch switch merge rebase cherry-pick

LearnGitBranching

分支管理

创建分支

1
git branch <branchname> [<start-point>]
  • start-point 是一个commit-ish,指定从何处创建分支

列出分支

1
git branch [-a]
  • -a 列出所有分支、显示隐藏分支

为本地分支设置默认上游分支

与《远程相关操作》配合,方便其pullfetchpush等操作

1
2
git branch (--set-upstream-to=<upstream> | -u <upstream>) [<branchname>]
git branch --unset-upstream [<branchname>]
  • <upstream> 上游分支
  • <branchname> 下游分支

删除、重命名、复制分支

1
2
3
git branch -d [-f] <branch-name>…​
git branch -m [<oldbranch>] <new-branch>
git branch -c [<oldbranch>] <new-branch>
  • -d 删除已被合并分支
  • -d -f 强行删除分支,不论已被合并与否
  • -m 重命名分支,新名称不得重名
  • -c 复制分支,复制出的分支名称不得重名

切换分支

1
git switch <branch-name>
  • 新建分支并立即切换过去

    1
    git switch -c <new-branch> [<start-point>]

合并分支

merge 合并(常用)

将指定分支合并进来,并产生一个新 commit

1
2
3
git merge [--no-commit]
[--[no-]allow-unrelated-histories]
[-m <msg>] [<commit>…​]
  • --no-commit 只合并不 commit
  • --allow-unrelated-histories 允许合并不匹配的历史
  • -m 指定 commit 消息
  • <commit> 指定要被合并进当前分支的 commit 或分支名们
合并时遇到冲突

当 commit 间存在冲突,合并操作会被暂停,此时:

  • 可以使用 git mergetool 解决冲突,再用 git merge --continue 继续合并
  • 可以使用 git merge --abort 中断当前的合并,尝试回退至合并前状态

rebase 合并(少见)

将调整 commit 间的顺序,通过“嫁接”的方式合并。通常用于将个人 commit 整洁地排序

1
git rebase [-i] [--onto <newbase>] [<upstream> [<branch>]]
  • -i 交互式操作
  • --onto <newbase> 是“嫁接”的砧木,可以是分支名或 commit 号;
    如未指定,则 <newbase><upstream>
  • <upstream> 是“嫁接”接穗的原本主枝;如未指定,为现在分支对应的远端分支
  • <branch> 是“嫁接”接穗;如未指定,为当前所在分支
1
git rebase (--continue|--skip|--abort|--quit|--edit-todo|--show-current-patch)

当 rebase 过程中出现冲突,我们需要手动处理(通过 git add),然后使用这些命令选项继续、中断或跳过等等

注意 rebase 有能力修改历史!

cherry-pick 合并(少见)

仅合并指定 commit