Search code examples
gitbranchgit-diff

How to git-diff a single, staged file with same file in other branch


If I understand correctly, if I do

git diff master devel ./my_file

I get the diff between the two HEADs of the branches. However, if I have made changes in, say, master and staged them, I thought I could get the diff between the unstaged file and the corresponding file in the other branch with

$ git diff --cached master devel ./my_file

but I get the following error:

usage: git diff [<options>] [<commit> [<commit>]] [--] [<path>...]

So what is the correct way to get the diff between staged changes in a file and the corresponding file in another branch?


Solution

  • Try the following syntax:

    git diff --cached devel -- my_file.ext
    

    This should compare my_file.ext as it is at the HEAD of the devel branch against the current stage in master (assuming you run this command on the master branch).

    There is a lot going on in this command, but note that --cached does not refer to devel, which is a commit where the concept of stage does not apply. Instead, --cached refers to the file my_file.ext which follows the -- separator.

    This command corresponds to the following pattern from the manual:

    git diff [--options] --cached [<commit>] [--] [<path>…​]
    

    Here devel is the commit and my_file.ext is the file path.