First, let me state that this is a programming question (and thus does not belong on superuser et. al.) because I'm talking shell programming. This could almost be a golf question, but I do not have an answer to begin with, so any help would be appreciated :-)
So, the story is: I like to pipe stuff into less
with the --quit-if-one-screen
option because it is very comfortable: less
does not get in my way when unnecessary. Or does it ? When my prompt is already at the bottom of my terminal window, this option does exactly what I want (i.e. less
behaves like cat
). But, when my current prompt is at the top of the window, less
first prints plenty of blank lines to clear the screen, then prints out my (short) file at the bottom of the screen, and only then it realizes that there is less text than one screen, so it exits and I get my prompt back.
But this behaviour is not great, because of all those useless blank lines. I tried different options, or wrote scripts and aliases, and the best I could come up with would be this (I'm using zsh, so the shell is already capable of duplicating pipes and so on):
function catless() {
cat \
>>( bucket -$LINES | cat ) \
>>( bucket +$LINES | less )
}
Where bucket
is another script I just wrote, which copies stdin to stdout if it is less than N lines (with -N) or more than N (with +N).
I posted it here: http://snipt.net/Gyom/copy-stdin-to-stdout-or-not-depending-on-length
And ls | catless
almost-works. But, for synchronization reasons, the different processes involved here do not get access to the terminal correctly and everything executes in the background (in particular, I never get a correct less
here, and the prompt comes back too soon). But maybe I took the wrong path.
So, to summarize, what I want is such a function/script/whatever that I can type ls | catless
and it behaves exactly like ls | cat
when the output of ls
is shorter than one screen, and like ls | less
when longer.
Any ideas ?