Q:

Automatically truncating long output in bash

Is it possible to automatically truncate long output in bash?
Ideally I would like to define a limit, say MAXLINES, and automatically apply tail -n $MAXLINES to every command that outputs more than MAXLINES lines to the terminal (but not in other contexts, e.g. pipes, obviously).

A:

May be done using PROMPT_COMMAND
MAXLINES=10
tmp_out=/tmp/$$.output
PROMPT_COMMAND='touch "$tmp_out"; tail -n "$MAXLINES" "$tmp_out" >/dev/stdin; exec >"$tmp_out"'

How it works

tmp_out=/tmp/$$.output temporary file used to store output of command
touch "$tmp_out" : create empty file if doesn't exist so that tail command doesn't fail at first call
tail -n "$MAXLINE" "$tmp" > /dev/stdin : show first maxlines of output
exec > "$tmp_out" : clear temporary file and redirects current process output (file descriptor 1) to this file, in case stderr can also be redirected to another file to be truncated (for example 2> "$tmp_err").

To run a command without redirection
exec >/dev/stdin; ... the command

or (space after { is important)
{ the command;}>/dev/stdin

To retrieve inital settings
unset PROMPT_COMMAND; exec >/dev/stdin

