7

The default behaviour of git diff — syntax-colored, paged — is very nice to work with, but it would be slightly nicer with line numbers for context, particularly for larger diffs, and especially for the final page.

git diff | nl | more

almost gives me everything I need, but it discards the coloring; any way I can get that back?

10

use less -r to display the colour, but you will need to force git to use colours because when you pipe git diff it will difault to --nocolor

git diff --color HEAD~3 HEAD | nl | less -R

If you like to get the line numbers per line, try looking about the solutions suggested here, https://stackoverflow.com/questions/24455377/git-diff-with-line-numbers-git-log-with-line-numbers

1
  • 3
    Using less -R outputs only ANSI "color" escape sequences in "raw" form. Jan 15 '17 at 15:12
1

Instead of piping git log, you can use less's built in line-numbering. Typing -N in less will cause it to display line numbers.

1
  • I always forget quite how configurable git is. This lets me set the pager options globally and I don't have to manually pipe anything anymore. Thanks; I've added the full command I used in my own answer.
    – Bobby Jack
    Jan 19 '17 at 11:06
1

Dylan Frese's answer got me investigating a bit, and I believe this solution to be slightly better than the one I previously accepted; for my purposes, anyway.

git config --global --replace-all core.pager 'less -NR'

This then lets me git diff and not even have to think about it. Of course, there are occasions where you might not want this to be a permanent, global change, so the info. here is all still valid.

1

Use command:
git diff --color=always | less -RN

And could define a shortcut command in ~/.bashrc:

alias gdc='git diff --color=always | less -RN'

-1

Try showlinenum and pipe it to less -R, e.g.

git diff --color=always | showlinenum.awk | less -R

About showlinenum, just clone the github repo and copy showlinenum.awk to PATH. The script will give you exact line number.

Also you may want to use git difftool. If you're comfortable with less, then vimdiff (git difftool -t vimdiff) is a nice idea:

Read man git-difftool for more.

2
  • 1
    showlinenum.awk is a script that you have on your local machine?
    – Bobby Jack
    Jan 15 '17 at 15:18
  • No it's available on Github. Sorry I didn't make the link clear.
    – McSinyx
    Jan 16 '17 at 2:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.