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

痞子三分冷 提交于 2019-12-17 17:26:14

问题


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.


回答1:


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



回答2:


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



回答3:


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.

You can check this response:

Compare a file from two different branchs in Git




回答4:


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>



回答5:


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

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


来源:https://stackoverflow.com/questions/8131135/git-how-to-diff-two-different-files-in-different-branches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!