Compare Two Files In Different Branches With Git

Ever wanted to do a quick diff between two different files in two different commits with git? Then read on, here’s how you can do it…

Goal

  • Compare two files in two commits with git
  • Commit may be anything denominatable by git (commit, branch, HEAD, remote-branch)
  • Name / Path may differ
  • Branch may differ

Tip

Syntax

git diff BRANCH:PATH OTHER_BRANCH:OTHER_PATH

Examples

  • Compare two different files in two different branches:
    git diff branch_a:file_a.txt branch_b:file_b.txt
    
  • Compare a file with another version of itself in another commit
    git diff HEAD:file.txt a09127a:file.txt
    
  • Same as above, but the commit is denominated by its branch:
    git diff HEAD:file.txt branchname:file.txt
    
  • Same as above, but with shortcut-syntax for the currently checked-out commit:
    git diff :file.txt branchname:file.txt
    
  • Compare a file with itself four commits ago (readable syntax):
    git diff :file.txt HEAD~4:file.txt
    
  • Compare a file with itself four commits ago (handy syntax):
    git diff :file.txt HEAD~4:file.txt
    
  • Compare a file with its latest version in the origin-repository:
    git diff :file.txt remotes/origin/master:file.txt
    
  • Compare a file with its fourth-latest version in the foo-branch of the bar-repository:
    git diff :file.txt remotes/bar/foo~4:file.txt
    

Explanation

If the path (aka object name) contains a colon (:), git interprets the part before the colon as a commit and the part after it as the path in the tree, denominated by the commit. (For more details refere to this post with tips for git show)

Leave a Reply

Your email address will not be published. Required fields are marked *