我有两个不同分支中的文件,如何在一个命令中对它们进行比较?
类似这样的操作:
# git diff branch1/foo.txt branch2/foo-another.txt
我可以检出另一个文件,进行差异比较并还原,但那是相当糟糕的解决方案。
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
git help diff
中推断出来。顺便说一下,冒号前面不必是分支名称,而可以是任何类型的提交引用(例如SHA-1值)。 - Steve Jorgensengit difftool
,然后删掉 branch2:
,这将允许你在当前工作树中编辑一个文件(以将更改从 branch1
搬运过来)。 - gMale注:不需要完整的路径,您可以使用相对路径./
开始。有时很方便。
git diff branch1:./relative/path/to/foo.txt branch2:./relative/path/to/foo-another.txt
离题回答 -- 在不同分支中比较同一文件的差异
仅补充说明一下,因为我认为这是非常直观的语法:
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>
有许多方法可以比较两个不同分支的文件。例如:
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=somebranch
branch2=someotherbranch
git diff ${branch1}..${branch2} -- file_path