How to make program help text automatically pipe through less?

Just now, dpkg --help spit out three pages of output in my face. I was maybe interested in the first ten lines, which show the general usage and most common arguments.

I’d like that, whenever I run a program (any program) with --help as the only argument, if the output is longer than $(tput lines), it would automatically get piped through less. Is it easily doable in bash?

Edit: In the end, the best solution for me was to switch to zsh. Either one of the following snippets in your ~/.zshrc will do the job; each one has its own tradeoffs:

# Modify the input line before it runs
function lessify() {
    if [[ "$BUFFER" =~ " --help$" ]] ; then
        BUFFER="$BUFFER | less -FX"
    zle accept-line

zle -N lessify_widget lessify
# Bind to the Enter key
bindkey '^M' lessify_widget


# Alias --help ; ignore rest of the line 
alias -g -- --help="--help | less -FX ; true "

Also, in researching this question, I’ve probably wasted more time than this will ever save me. Don’t regret it one bit.

Asked By: Mihai


In bash, you can do this with the debug features, although it’s a pretty fragile solution and very dependent on your environment.

Enable extended debugging (see the manual for details):

shopt -s extdebug

Create a helprun function:

helprun() {
    if [ "$#" -eq 2 ] && [ "$2" = '--help' ]; then
        "$@" | less -F
        return 1

Then trap all commands with it:

trap 'helprun $BASH_COMMAND' DEBUG

This will run helprun <command> for every command, and if it is a --help command, pipe it through less, returning 1 so that the command isn’t executed (thanks to extdebug). If it isn’t, it just runs as normal.

There are probably edge cases I haven’t handled here…

Answered By: Stephen Kitt

Alternative method is to write a script which does the same:

$1 --help | less -F

Call it Help for example, chmod +x Help to make it an executable and place it somewhere in your PATH, such as /bin or /usr/bin.
Then everytime you want to list the help of a program, you use Help <program> instead of <program> --help.

Answered By: Simon Klaver
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.