Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare files from two different branches

Tags:

git

git-diff

I have a script that works fine in one branch and is broken in another. I want to look at the two versions side-by-side and see what's different. Is there a way to do this?

To be clear I'm not looking for a compare tool (I use Beyond Compare). I'm looking for a Git diff command that will allow me to compare the master version to my current branch version to see what has changed. I'm not in the middle of a merge or anything. I just want to say something like

git diff mybranch/myfile.cs master/myfile.cs 
like image 573
Micah Avatar asked Nov 04 '10 18:11

Micah


People also ask

How do I compare files in two branches?

Compare specific file between two branches In some cases, you may want to see all changes done to a specific file on the current branch you are working on. In order to see the differences done to a file between two branches, use the “git diff” command, specify the two branches and the filename.

How can I compare two files for differences?

Right-click on the first file. Click on “Select for Compare” from the menu. Proceed to right-click on the second file. Click on “Compare with Selected.

How do you compare two branches and codes?

To add some details on usage, the way I found to compare branches in Git Lens is to; Open the Explorer view (Ctrl + Shift + E), find the Git Lens group, right click the branch you want to compare and select 'Select for Compare',then right click the second branch and select 'Compare with Selected'.


1 Answers

git diff can show you the difference between two commits:

git diff mybranch master -- myfile.cs 

Or, equivalently:

git diff mybranch..master -- myfile.cs 

Note you must specify the relative path to the file. So if the file were in the src directory, you'd say src/myfile.cs instead of myfile.cs.

Using the latter syntax, if either side is HEAD it may be omitted (e.g., master.. compares master to HEAD).

You may also be interested in mybranch...master (from git diff documentation):

This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. git diff A...B is equivalent to git diff $(git-merge-base A B) B.

In other words, this will give a diff of changes in master since it diverged from mybranch (but without new changes since then in mybranch).


In all cases, the -- separator before the file name indicates the end of command line flags. This is optional unless Git will get confused if the argument refers to a commit or a file, but including it is not a bad habit to get into. See Dietrich Epp's answer to Meaning of Git checkout double dashes for a few examples.


The same arguments can be passed to git difftool if you have one configured.

like image 144
dahlbyk Avatar answered Sep 22 '22 07:09

dahlbyk