How to compare files from two different branches?

 

To compare files from two different branches in Git, you can use various Git commands and tools. Here's a step-by-step example using the git diff command:

Suppose you have two branches, branch1 and branch2, and you want to compare a specific file between these branches.

bash
# Navigate to your Git repository cd /path/to/your/repository # Compare a specific file between two branches (e.g., branch1 and branch2) git diff branch1 branch2 -- path/to/your/file.txt

In this example:

  1. Navigate to your Git repository using the cd command.

  2. Use the git diff command to compare a specific file between the two branches. Replace branch1 and branch2 with the names of the branches you want to compare and path/to/your/file.txt with the path to the file you want to compare.

    For example, if you want to compare file.txt between master and feature-branch, you would use:

    bash
  1. git diff master feature-branch -- file.txt
  2. Running the command will display the differences between the two versions of the file. It will show additions, deletions, and modifications, indicating how the file differs between the two branches.

Here's an example of what the output might look like:

plaintext
diff --git a/path/to/your/file.txt b/path/to/your/file.txt index abcdef1..1234567 100644 --- a/path/to/your/file.txt +++ b/path/to/your/file.txt @@ -1,5 +1,5 @@ This is some content in file.txt -Line added in branch1 +Line added in branch2 More content in file.txt -Change in branch1 +Change in branch2 Even more content

This output provides a line-by-line comparison of the file, indicating what has changed between the two branches.

You can use the git diff command to compare files not only between branches but also between commits, tags, and other references in your Git repository.

Comments