6

If I do git diff, I'll get the current changes of all unstaged files.

Is there a simpler way to automatically perform git diff on just the first listed file (using the built in flags)?

The best I've come up with is:

function git_diff_first_unstaged_file() {
    if [[ $(git diff --name-only) ]]; then
      git diff $(git diff --name-only | sed -n '1 p')
    else
      echo "gdf: There are currently no unstaged changes."
    fi
}
alias gdf='git_diff_first_unstaged_file'

I'm wondering if there is a git diff flag I brushed over that would do this for me.

FractalSpace
  • 5,577
  • 3
  • 42
  • 47
Nico
  • 399
  • 1
  • 15
  • 1
    There is no flag. Your method is as good as any (more or less: you could make it a bit more efficient by running just the one `git diff --name-only | sed -n 1p`, saving the output in a variable, and then running `git diff` on that saved name only if there was a name). – torek Nov 21 '16 at 23:51
  • 1
    I think I could just do `git diff $(git diff --name-only | sed -n 1p)`, but the if statement is nice. Regardless, thanks for confirming my sanity about the potentiality of a flag :) – Nico Nov 21 '16 at 23:57
  • I have to ask... why do you want this? – Schwern Nov 22 '16 at 00:29
  • 1
    Before I add code to a commit, I like to git diff all changed files. I could do `git diff` alone, but often times it's just way too much. Rather than doing "git status" and seeing all the files that are unstaged but modified, I can just do this and automatically diff the first one. I made one for `git add` as well. – Nico Nov 22 '16 at 16:12

2 Answers2

5

Beside git diff --name-only, you also have git ls-files --modified that would list you unstaged files (to be used with | sed -1p to get the first one).

Don't forget that if you want to start staging diff for the first file, you have the option to simply type:

git add -p

You will see and will be able to selectively add diffs for the first file (and then the second, at which point you can type q to quit the interactive staging session)

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
4

Following the recommendations in the comments, one can add the following alias to ~/.gitconfig (of project config) in order to make a diff only with the first unstaged but tracked file:

[alias]
    gdf = "! git diff $(git diff --name-only | sed -n 1p)"

If you want to make a diff with the i-th unstaged but tracked file:

[alias]
    gdi= "!f() { git diff $(git diff --name-only | sed -n $1p); }; f" 

git gdi 3 will show diff of unstaged changes of third file (or last file if there are less than 3 files).

x0s
  • 1,648
  • 17
  • 17