home | list info | list archive | date index | thread index

Re: [OCLUG-Tech] least: bash pager hack

Bart Trojanowski wrote:
I wanted to have a pager that would decide if the text was being worth
paged.  That is a pager that behaved like cat if the text would fit on
the screen, and would behave like less if the text would not fit on the
screen.

Here is my attempt:

http://www.jukie.net/~bart/scripts/least/bashrc.least

This is the first time I've used bash arrays, and am not a huge fan. :)

Can any of you bash gurus find a way to shorten the code?

I don't claim to be a guru, but here's one attempt...

function least() {
if [ -n "$*" ]; then
	cat "$@" | least
	return $?
fi

case "$LINES" in
	'') LINES=20 ;;
	*[^0-9]*) LINES=20 ;;
esac

start="$(head -$(($LINES + 1)))"
if [ $(printf "%s" "$start" | wc -l) -le $LINES ]; then
	printf "%s" "$start"
else
	( printf "%s" "%start"; cat; ) | $PAGER
fi
}


Warning: I haven't tested this, not even for syntax errors, and I haven't really thought it through. There are certainly errors of generality (this is Ian!'s cue... :-)). For one thing, lines long enough to wrap might throw it off - but you knew that.

Also, if your pager is vim, you could try using a vim script. This would probably allow a more accurate test for whether the file fits on one page.

And, for those who use less, there's 'less -F' or 'less -XF'.

replies

references