How to use git diff to compare files from different branches?
Hello there and welcome back to my blog! Today we are going to talk about how we can use git diff in order to compare the changes that are made in files belonging to s specific directory in your repository.
The git diff command
First, let's look at the git diff command syntax for our usecase.
git diff [<options>] <commit>..<commit> [--] [<path>…]
<commit> is a branch name, a commit hash, or a shorthand symbolic reference.
Example scenario
Let's say that you want to compare all the changes that have gone in to branch1 and branch2 for a set of files that match a certain regex. This is going to be a common scenario when you have a release branch and another mainline branch and you want to compare the differences in the files from thses two branches.
For the sake of this example, lets say that I want to compare all the files that belong to a directory: directory1
and the branches that I want to compare are: main
and production_branch
.
The commands that you can use locally are:
#fetch the latest code from remote
git fetch
#compare the branches for all files under directory1
git diff --name-only origin/main origin/production_branch -- directory1/
> --name-only will display only the files that have changed. Remove that option if you want to see the actual diffs.
Note that there are multiple ways in which you can use this command, I have used it in this way only to compare the file names that have changed under the directory directory1
.
Here are some of the references: