4

Some shell commands that produce large outputs, such as git diff, seem to cleverly throw up a pager when the output is too long, but not do so if it happens to be small.

How does this work? Does each individual program have its own code to measure its output, and invoke the pager? By the time it realizes the output is too long, wouldn't it have already printed some to stdout with no way to get it back? Or is this a generic shell feature where any program can be made to take advantage of it even if not explicitly programmed to do so?

To be clear: Of course foo | less will force a pager and foo | cat will force no pager. What I'm wondering is if there's a way to make any arbitrary foo behave as foo | pager_if_needed. I also don't mean literally implementing pager_if_needed (probably can be done in 2-3 lines of bash) and doing alias foo="foo | pager_if_needed" - since that would not also apply to bar, baz, and everything else.

1

1 Answer 1

2

How does the shell decide when to invoke a pager?

It doesn't.

Does each individual program have its own code to measure its output, and invoke the pager?

Yes.

By the time it realizes the output is too long, wouldn't it have already printed some to stdout with no way to get it back?

Simple: only start printing your output after you have checked whether it is too long.

4
  • 3
    for the last one, I think git relies on less -F to have less itself exit if the output fits the screen.
    – ilkkachu
    Commented Sep 21, 2021 at 20:51
  • But I assume only if Git uses less, correct? The pager for Git can be configured separately for each command per repository, per user, and per system, as well as using the GIT_PAGER and PAGER environment variables. Commented Sep 21, 2021 at 21:02
  • Yes, and even with less, you could set LESS to something that doesn't include -F, and you'll see the pager appear if the output from the Git command is short enough. What I mean is that it looks to me that Git doesn't really care how long the output is, but instead punts that part of the UI to the pager.
    – ilkkachu
    Commented Sep 21, 2021 at 21:04
  • @ilkkachu Ah so less -F is already behaving like the hypothetical pager_if_needed from my question. Neat.
    – Haterind
    Commented Sep 21, 2021 at 23:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .