Andy Stewart
Andy Stewart

Reputation: 5498

Is it possible to git-diff a file against standard input?

Let's say I'm editing a file. If I save the file, git-diff will give me its changes relative to the index. I'd like to get the changes relative to the index without saving the file first – for a "realtime" diff.

One solution is to write the unsaved changes to a temporary file (i.e. save the file elsewhere), write the staged file to another temporary file (git show :file > tempfile2) then git-diff tempfile tempfile2. However that seems inelegant.

Is there a better way?

Upvotes: 17

Views: 6540

Answers (2)

Ash Berlin-Taylor
Ash Berlin-Taylor

Reputation: 4048

Since git 1.5.1 there's been an option to diff against stdin - it's just not been documented

$ echo foo | git diff --no-index -- my_file -

On playing with this a bit more I realized this might not be what the OP (or I) wanted - it diffs the current state of the file to stdin, not the last committed state of the file to stdin. Something like this will do that

$ echo foo | diff -u <(git show :my_file) -

Note this does mean invoking diff directly which might not pick up some settings in your git config. Basically as ams says in his answer.

Upvotes: 17

Kelvin
Kelvin

Reputation: 20867

Improving upon Ash Berlin's answer.

This allows you to use the nice features of git-diff.

git show :file | git diff --no-index -- - temp_saved_path

Note that this still might not be as convenient as you'd like, because you still have to write to a temp file. Until you save the file, the changes are either not on disk at all (in-memory only), or in some kind of temporary file that is editor-dependent. It's possible that Vim could do this seamlessly in one step, but I'm not familiar enough to say.

Upvotes: 4

Related Questions