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

前端 未结 5 655
梦如初夏
梦如初夏 2021-02-01 03:41

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 t

相关标签:
5条回答
  • 2021-02-01 03:59

    You could always pipe to less -E (this will cause less to automatically quit at the end of the file). For commands with short output it would do what you want. I don't think you can automatically pipe to less when there is a lot of output.

    0 讨论(0)
  • 2021-02-01 04:08

    Pipe it to less -F aka --quit-if-one-screen:

    Causes less to automatically exit if the entire file can be dis- played on the first screen.

    0 讨论(0)
  • 2021-02-01 04:14

    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.

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

    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.

    0 讨论(0)
  • 2021-02-01 04:14

    I wrote this wrapper function and put it in my .profile. You can use this before a command and it will automatically pipe it to less if it is longer than 1 page.

    lcmd ()
    {
        echo "$("$@")" | less -F;
    };
    

    So 'lcmd ls' would ls the current directory and pipe that output to less.

    0 讨论(0)
  • 2021-02-01 04:22

    In general, automatically piping to less requires the shell to be prescient about the output that will be produced by the commands it runs - and it is hard enough for humans to predict that without trying to make programs do so.

    You could write a shell that does it for you - that captures the output (but what about stderr?) and paginates if necessary, but it would most certainly not be a standard shell.

    0 讨论(0)
提交回复
热议问题