Git:如何比较不同分支中两个不同文件的差异?

221
我有两个不同分支中的文件,如何在一个命令中对它们进行比较? 类似这样的操作:
# git diff branch1/foo.txt branch2/foo-another.txt

我可以检出另一个文件,进行差异比较并还原,但那是相当糟糕的解决方案。


5
这不是重复问题,因为这个问题询问如何在不同分支中比较不同的文件。而链接的问题只询问如何比较不同分支中的相同文件 - Steve
如果一个或两个文件在工作树(文件系统)中,考虑这个问题。 - Josiah Yoder
5个回答

279
git diff branch1:full/path/to/foo.txt branch2:full/path/to/foo-another.txt

你也可以使用相对路径:

git diff branch1:./relative/path/to/foo.txt branch2:./relative/path/to/foo-another.txt

11
太棒了!我肯定无法从 git help diff 中推断出来。顺便说一下,冒号前面不必是分支名称,而可以是任何类型的提交引用(例如SHA-1值)。 - Steve Jorgensen
3
重要提示:在Windows上使用Git时,需要将完整的itemspec指定为Unix名称。例如,branch1:full\path\to\foo.txt会失败,而branch1:full/path/to/foo.txt可以正常工作,没有分支时也可以使用full\path\to\foo.txt。 - Eris
使用 git difftool,然后删掉 branch2:,这将允许你在当前工作树中编辑一个文件(以将更改从 branch1 搬运过来)。 - gMale
1
在Linux上尝试使用Git版本1.8.3.1,只允许使用相对路径。 - Sola Yang

25

注:不需要完整的路径,您可以使用相对路径./开始。有时很方便。

git diff branch1:./relative/path/to/foo.txt branch2:./relative/path/to/foo-another.txt

12

离题回答 -- 在不同分支中比较同一文件的差异

仅补充说明一下,因为我认为这是非常直观的语法:

git diff <branch1> <branch2> <filepath>

同样适用于相对引用,例如:

# compare the previous committed state from HEAD with the state branch1 was 3 commits ago
git diff HEAD^ <branch1>~3 <filepath>

5
楼主明确要求“不同的文件”,而你的回答是关于比较两个不同分支中相同文件的内容。请重新回答问题。 - Étienne Miret
1
@EtienneMiret 您说得完全正确,我错过了那个重要的点。这是一个离题的回答。 - Romain Valeri
4
许多人会遇到这个问题,因为他们想了解同一文件的区别,而这个答案是有用的。 - Matthieu
@Matthieu 那为什么不链接到相关的答案呢? - jtlz2
1
@jtlz2 我不确定我理解了。这个答案对于那个问题是相关的(虽然不是 OP)。原因是谷歌把我们带到了这里 ;) - Matthieu

4

有许多方法可以比较两个不同分支的文件。例如:

  • If the name is the same or different:

     git diff branch1:file branch2:file
    

    Example:

     git diff branch1:full/path/to/foo.txt branch2:full/path/to/foo-another.txt
    
  • Only if the name is the same and you want to compare your current working directory to some branch:

    git diff ..someBranch path/to/file
    

    Example:

    git diff ..branch2 full/path/to/foo.txt
    

    In this example you are comparing the file from your actual branch to the file in the master branch.

您可以查看此响应:

在Git中比较来自两个不同分支的文件


这是误导性的。它将“最新提交”与当前分支进行比较,而不是将当前工作目录中实际找到的文件(如果存在未提交的更改)与其他分支进行比较。您的措辞暗示它会比较磁盘上实际找到的文件,但事实并非如此。 - Hammerite

-1

您可以指定应用于 git diff 的起始位置和范围。范围使用 .. 表示。

branch1=somebranch
branch2=someotherbranch
git diff ${branch1}..${branch2} -- file_path

1
这只是比较两个分支中相同文件的内容;问题是关于在两个分支中比较两个不同文件的内容。 - Piran
@Piran和我遇到了这个问题,因为我想比较两个分支中的同一文件,所以我很高兴有这个答案存在。 - Matthieu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接