Git:如何在不同的分支中区分两个不同的文件?

Ond*_*žka 162 git git-diff

我在不同的分支中有两个不同的文件.如何在一个命令中区分它们?

就像是

# git diff branch1/foo.txt branch2/foo-another.txt
Run Code Online (Sandbox Code Playgroud)

我可以看看另一个文件,差异并恢复,但这是非常脏的解决方案.

twa*_*ggs 208

git diff branch1:full/path/to/foo.txt branch2:full/path/to/foo-another.txt
Run Code Online (Sandbox Code Playgroud)

您还可以使用相对路径:

git diff branch1:./relative/path/to/foo.txt branch2:./relative/path/to/foo-another.txt
Run Code Online (Sandbox Code Playgroud)

  • 真棒!我当然无法从`git help diff`推断出这一点.顺便说一句,那些不必是冒号之前的分支名称,但可以是任何类型的提交引用(例如SHA-1值). (8认同)
  • 重要说明:Windows上的Git要求完整的itemspec为unix名称.即branch1:full\path\to\foo.txt失败,而branch1:full/path/to/foo.txt工作正常,完整\ path\to\foo.txt(无分支) (3认同)

Cam*_*mpa 21

旁注:不需要完整路径,您可以从./相对路径开始.它有时候很方便.

git diff branch1:./relative/path/to/foo.txt branch2:./relative/path/to/foo-another.txt
Run Code Online (Sandbox Code Playgroud)


Rom*_*eri 12

题外话答案——在不同分支中比较同一文件

只是为了添加它,我发现它是一个非常简单的语法:

git diff <branch1> <branch2> <filepath>
Run Code Online (Sandbox Code Playgroud)

也适用于相对引用,例如:

# compare the previous committed state from HEAD with the state branch1 was 3 commits ago
git diff HEAD^ <branch1>~3 <filepath>
Run Code Online (Sandbox Code Playgroud)

  • OP 特别要求“不同的文件”。您的答案是比较两个不同分支中的同一文件。 (5认同)
  • 尽管如此,许多人还是会提出这个问题,因为他们想获得同一文件的差异,这个答案很有用。 (4认同)