Home > OS >  Git diff for n'th modified file?
Git diff for n'th modified file?

Time:02-07

Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js

and run

git diff app/assets/stylesheets/application.scss

then

git diff app/javascript/packs/application.js

and so on..

git diff app/views/layouts/application.html.erb

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?

CodePudding user response:

If you're working in a bash-like shell, you can define a shell function such as

function gitdiffn() {
    git diff ${@:2} $(git diff --name-only | sed -n "$1 p") 
}

which can then be used to browse the list of modified files (with 1-based indexing) as

$ gitdiffn 1
$ gitdiffn 2
# ...

By including ${@:2} before the $(command substitution) that fetches the nth file name, we allow for the propagation additional arbitrary flags to the git diff invocation, so commands like

$ gitdiffn 1 --minimal

will work as expected.

CodePudding user response:

You can use the search capability of less. That is, you type

git diff

as always, then type /^diff to search for the hunk headers, then type n until you arrive at the file you are interested in. Type N to search backwards.

less remembers recently used search patterns. Next time around it suffices to type n. Use up- and down-arrows to cycle through recently used patterns.

  •  Tags:  
  • Related