Is there a way to use git diff
to get a diff between two commits, but only show the diff for the files that exist in both commits?
I have a branch I created a couple of weeks ago, and our main code has diverged quite a bit from it by now. As a result, if I do a diff between my current HEAD and the tip of the old branch, I get dozens of changed files, but it's mostly just noise.
I really want to see a diff that shows only the files that exist in both branches. I know one way to do this would be to cherry-pick the other branch's commits on top of the current HEAD, but is there a way to do it just using git diff
?
You can run the git diff HEAD command to compare the both staged and unstaged changes with your last commit. You can also run the git diff <branch_name1> <branch_name2> command to compare the changes from the first branch with changes from the second branch. Order does matter when you're comparing branches.
You can compare files between two Git commits by specifying the name of the ref that refers to the commits you want to compare. A ref may be a commit ID or HEAD, which refers to the current branch. Let's compare two commits in our Git repository. The above command will perform a diff operation across our two commits.
The git diff command is used to perform the diff function on Git data sources. For example, commits, branches, files, and so on. It can also be used to compare two files of different branches.
To check the staged changes, run the git diff command along with --staged option.
The following may do what you want:
git diff --diff-filter=M commitA commitB
The M
option to --diff-filter
says only to include files that appear to be modified between the two commits - ones that only exist in one branch or the other would be selected with A
("added") or D
("deleted").
You can see which files would be selected with these letter codes by doing:
git diff --name-status commitA commitB
... and there's more information about all of that in the git diff
documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With