Compare file to another file in another commit

I have moved some code from a file to another file, and applied little changes in it. I would like to have a diff to see those changes.

The problem seems pretty common to me, but I have never needed to do such a thing. I only know how to compare the same file with himself in a previous revision, or 2 different files in the same revision.

  • How to unstash only certain files?
  • What is the workflow for contributing to an open source git repository?
  • Git checkout from repository on GitHub into an existing local repository based on SVN
  • How can I rebase as one commit using Git
  • git rm - fatal: pathspec did not match any files
  • How to setup auto-completion with git on openBSD?
  • Are there git diff options to compare one file in the current revision to another file in another commit? Or any other way?

  • Workflow Git FTP for old projects with potential external non-git users
  • Difference between git pull . master vs git merge master
  • Line endings messed up in Git - how to track changes from another branch after a huge line ending fix?
  • What is best way to manage multiple related repositories with git?
  • How to change the default username of Git
  • git cloning gnome core suite
  • 2 Solutions collect form web for “Compare file to another file in another commit”

    I think this is what you are looking for. HEAD~3 can be replaced with the commit id.

    git diff HEAD~3:oldfile.xml file/in/another/path/newfile.xml
    

    A dirty but working solution

    Use git ls-tree to get the SHA1 identifier of the files on the commits you want to compare then use git diff [options] <blob> <blob> and provide the two SHA1 identifiers as arguments.

    $ git ls-tree commit1 dir1/dir2/file1.txt
    100644 blob 7d252b754d46a8fcd0613a96710c9326942d7a92   dir1/dir2/file1.txt
    
    $ git ls-tree commit2 dirA/fileB.txt
    100644 blob 4d000ed739c880a26686a2843dae6eeeb4109a37   dirA/fileB.txt
    
    $ git diff 7d252b754d46a8fcd0613a96710c9326942d7a92 4d000ed739c880a26686a2843dae6eeeb4109a37
    

    If you need to do this frequently you can even pack everything in a small shell script:

    #!/bin/bash
    
    # This script does not validate its command line arguments!
    
    COMMIT1=$1
    FILE1=$2
    COMMIT2=$3
    FILE2=$4
    
    BLOB1=$(git ls-tree $COMMIT1 $FILE1 | cut -f3 -d' ' | cut -f1)
    BLOB2=$(git ls-tree $COMMIT2 $FILE2 | cut -f3 -d' ' | cut -f1)
    
    git diff $BLOB1 $BLOB2
    

    Run it as:

    $ script.sh commit1 dir1/dir2/file1.txt commit2 dirA/fileB.txt
    
    Git Baby is a git and github fan, let's start git clone.