Lazer Lazer - 5 months ago 27x
Bash Question

How to automatically pipe to less if the result is more than a page on my shell?

Mostly, I will not use

| less
for each and every command from the shell.

Pipe to less is used only when I actually run the command without is and find out that it does not fit on the page. That costs me two runs of the same shell command.

Is there a way so that every time a command result is more than a display page, it automatically gets piped to less?


The most significant problem with trying to do that is how to get it to turn off when running programs that need a tty.

What I would recommend is that, for programs and utilities you frequently use, create shell functions that wrap them and pipe to less -F. In some cases, you can name the function the same as the program and it will take precedence, but can be overridden.

Here is an example wrapper function which would need testing and perhaps some additional code to handle edge cases, etc.

foo () {
    if [[ -p /dev/stdout ]]  # you don't want to pipe to less if you're piping to something else
        command foo "$@" | less -F
        command foo "$@"

If you use the same name as I have in the example, it could break things that expect different behavior. To override the function to run the underlying program directly precede it with command:

command foo

will run foo without using the function of the same name.