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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8131135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 12:17:30  来源:igfitidea点击:

Git: How to diff two different files in different branches?

gitgit-diff

提问by Ondra ?i?ka

I have two different files in different branches. How can I diff them in one command?

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

Something like

就像是

# git diff branch1/foo.txt branch2/foo-another.txt

I could check out the other file, diff it and restore, but that's quite dirty solution.

我可以检查另一个文件,比较它并恢复,但这是一个非常肮脏的解决方案。

回答by twaggs

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

You can also use relative paths:

您还可以使用相对路径:

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

回答by Campa

Sidenote: no need for full paths, you can start with ./for relative paths. It can be handy sometimes.

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

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

回答by Javier C.

There are many ways to compare files from two diferents branchs. For example:

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

  • 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 diff branch1:file branch2:file
    

    例子:

     git diff branch1:full/path/to/foo.txt branch2:full/path/to/foo-another.txt
    
  • 仅当名称相同并且您想将当前工作目录与某个分支进行比较时:

    git diff ..someBranch path/to/file
    

    例子:

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

    在此示例中,您将实际分支中的文件与 master 分支中的文件进行比较。

You can check this response:

您可以查看此回复:

Compare a file from two different branchs in Git

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

回答by RomainValeri

Off-topic answer -- see comments

题外回答——见评论

Just to add it for I find it a very straightforward syntax :

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

git diff <branch1> <branch2> <filepath>

Also works with relative refs like for example :

也适用于相对参考,例如:

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

回答by JCF

You can specify a start and range for git diffto be applied to. The range is indicated with the ..notation.

您可以指定git diff要应用的开始和范围。范围用..符号表示。

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