I wrote a script to display git diff. It will

  1. display the difference in stdout if the output fits in the terminal screen, or
  2. display the difference in pager otherwise.

My script:


if ! git diff "$@" > /dev/null; then
    # not in a Git repository
    exit 1

if [ `git diff "$@" | wc --lines` -gt `tput lines` ]; then
    git diff "$@" --color=always | less
    git diff "$@" --color=always | cat

The current limitations of the script:

  1. If I need to do the same with git show or git log, I need to write another two similar scripts (which is not DRY).
  2. Auto-completion does not work. I need to write my own one (taking too much time).

Now I wish to write a script that does the same but works as a pager so that I can set Git configuration core.pager as the script and solve the problem mentioned.

Note: I am using Zsh.


I tried less --no-init --quit-if-one-screen (less -FX), and it does almost what I need, except that it will not clear the screen in the more-than-one-page case. So actually I need the --no-init option to be conditional: disable initialization and quit if it fits one screen; no special action otherwise. Maybe less --no-init-if-one-screen --quit-if-one-screen?

  • Not really relevant, but why are you piping through cat? – Sean Allred Jan 2 '16 at 13:49
  • @SeanAllred Because currently my core.pager is set as less. If it is not set at all, then I guess indeed I do not need to pipe through cat. – Franklin Yu Jan 2 '16 at 14:03
  • 1
    I think what you need is the -F option of less. – muru Jan 2 '16 at 15:40
  • You mean like git -p diff ...? – vonbrand Jan 2 '16 at 16:35
  • @muru The -F/--quit-if-one-screen does detect the size and quit as I required, but I hope that it can also display the content to stdout instead of a simple exit. less -FX (--no-init --quit-if-one-screen) will do everything except that I want it to clear the screen if it is more than one screen. – Franklin Yu Jan 4 '16 at 8:29

Your Answer

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

Browse other questions tagged or ask your own question.