1

I just created a script to display the contents of a file, either with cat or with less based on the number of effective (post-line-wrap) number of lines in the file. To be clear, what I have works well, I'm just curious if anyone has something better handy.

if [ $(stat -c '%s' "${ERRLOG}") -gt 0 ]; then
    echo "${ERRLOG}"
    if [ -n "${COLUMNS}" -a "$(grep -o ".{0, ${COLUMNS}}" "${ERRLOG}" | wc -l)" -gt "${ROWS}" ]; then
        less "${ERRLOG}"
    else
        cat "${ERRLOG}"
    fi
fi

While I'm rather proud of using grep -o, which splits multiple pattern matches within the same source line into multiple lines, I suspect there's a better way to do this, preferably one that does not parse through the contents of the file twice. Maybe something with awk?

Credit to this post for the use of $ROWS and $COLUMNS

xhienne
  • 5,738
  • 1
  • 15
  • 34
memtha
  • 797
  • 5
  • 24

1 Answers1

2

less has that functionality built-in:

-F or --quit-if-one-screen
Causes less to automatically exit if the entire file can be displayed on the first screen.

Options you always want to use can be set in the $LESS environment variable.

For less versions older than 530, the -X/--no-init option has to be used additionally; see the release notes for less 530:

Don't output terminal init sequence if using -F and file fits on one screen.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • That's not working for me. It quits without printing anything. Upvoted anyway because it's probably the right answer for most people. – memtha Apr 17 '20 at 14:34
  • @memtha What version of `less` do you have? Older version might require also setting `-X`/`--no-init`. – Benjamin W. Apr 17 '20 at 14:36
  • less 436 (c)1984-2009 Mark Nudelman ... greenwoodsoftware.com/less. The one that comes in mingw msys. Works with `-X`. Thx. Is `-X` portable or must I test less version? – memtha Apr 17 '20 at 14:37
  • @memtha It was fixed in less 530; I think always using `-X` doesn't break things. – Benjamin W. Apr 17 '20 at 14:42