Search code examples
bashless-unix

Bash test effective (paginated) lines of file before displaying


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


Solution

  • 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.