3

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?

loris
  • 450
  • 8
  • 20

1 Answers1

6

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Sorry for having written 'unstaged' rather than 'staged' in the orignal question. This works, but which case is it from the manpage? The synopisis and description there don't seem to cover branches. – loris Mar 27 '18 at 09:18
  • @loris Check my updated answer, it does match to the Git manual. – Tim Biegeleisen Mar 27 '18 at 09:22
  • You're right, although I find it a bit confusing, since my understanding is that a branch is a reference to a commit rather than being an actual commit. – loris Mar 27 '18 at 09:50
  • Git's manual is somewhat loose as technical documentation goes. As for the syntax, a branch name can be used to mean the HEAD commit of that branch, e.g. in a rebase. – Tim Biegeleisen Mar 27 '18 at 09:55
  • For the sake of completeness I'm including @Tim's answer to my original question, which was about getting the diff for an unstaged as opposed to staged file relative to another branch. His solution was `git diff devel:my_file -- my_file`. I haven't spotted the syntax with the colon in the man pages, but it is described here: https://git-scm.com/book/en/v2/Git-Internals-The-Refspec – loris Mar 27 '18 at 13:35