Let less work like cat, if only one screen full of text

On my Debian machine here, less always opens the alternate screen to show stuff.

This is annoying, if there are only 2 or 3 lines to be displayed. I'd like less to:

  • work as pager, if there is more than a screenful of information

  • and work like cat, if there's not.

Apparently, less has the -F flag for "single screen" cases:

-F or --quit-if-one-screen

Causes less to automatically exit if the entire file can be displayed on the first screen.

But in my case it just exits again, and no info is displayed. It's more like cat /dev/null and thus not really useful.

Has anyone an idea, how to achieve this less behaviour?


Solution 1:

You can combine -F with -X, which disables the terminfo initialization sequence.

export LESS=-FX

This has the (dis)advantage that less does not clear displayed text on exit, no matter how long the file was.

Solution 2:

As mentioned by grawity, you can pass -F -X to achieve this, but it means less will leave lots of text in your terminal scrollback (and it might not even be in order, if you jump around the text in less). less outputting nothing when you only pass -F is known issue #303.

Instead you can use a wrapper script. For slow inputs, like git log -Gregex, do you want:

A) lines to appear on the main screen as they come in, then switch to the alternate screen once scrolling is needed (so the first $LINES of output will always appear in your scrollback); if so, go with the 2nd of Gilles's answers to a similar question.

B) lines to appear on the alternate screen, but quit the alternate screen and print the lines to the main screen if scrolling turns out to be unnecessary (so no output will appear in your scrollback if scrolling was required); if so, look at my answer to a similar question.

Solution 3:

You could create a small wrapper script, like so:

#!/bin/bash
if (( $(wc -l < "$1") < ${LINES:-20} ))
then
        cat "$1"
else
        less "$1"
fi

If you create that in /usr/local/bin or ~/bin as a file called something like less2 (you might want to use a very short name like l for easy typing), and make sure it is executable with chmod a+x /usr/local/bin/less2, you can use it in place of less for commands of the form less filename, i.e., less2 filename (or l filename).

This won't work if you are piping another command’s output through less, or if you specify option(s) or multiple filenames.

It will no doubt be possible to do the same thing without the extra script file, by defining an alias a function, if you prefer.