获取 Git 中两个分支之间的差异

我做了以下事情(我将其与现实进行了简化) :

  • 创建了一个分支 第一科,切换到它
  • 添加文件 档案1和修改现有文件 文件2并提交此
  • 发现我不需要 档案1就把它取出来了

因此,原来的分行第一科之间的实际区别只是 文件2的修饰。

我想得到分支之间的实际差异,然后放入 第2科。一般来说,我想摆脱不必要的历史添加/删除 档案1

84843 次浏览

This is a simple git diff

git diff --name-only SHA1 SHA2

Where SHA1/2 are the hashes of the 2 commits at the top of each branch.

Or you can do

git diff --name-only develop...

To compare your branch against the develop branch

Let's assume that you started on the branch master. Then you can do:

git diff master Branch1 > ../patchfile
git checkout Branch2
git apply ../patchfile

Alternatively, if your goal is to rewrite history, then you could use an interactive rebase to squash commits.

I would do an interactive rebase on HEAD~2 and squash the last two commits together. Assuming that you want to keep the history as is in Branch1 and simplify it in Branch2, do the following (current branch Branch1):

git checkout -b Branch2
git rebase -i 'HEAD~2'

An editor will open up, showing something like

pick 1b58da0 Added File1, changed File2
pick d3f4f51 Delete File1

and many explanatory comments how rebasing works. Change the last commit to a squash and close the editor.

pick 1b58da0 Added File1, changed File2
squash d3f4f51 Delete File1

A new editor will open up where you can specify the new commit message. It would probably now just read

Changed File2

Close it and you're done, both commits are squashed together on Branch2 and Branch1 retains your original history. Note that if you don't need to retain the original history, you can just skip checking out Branch2 and work directly on Branch1. Only do that if you haven't published your last two commits on Branch1 already.