0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

You might first want to open a new shell with bash. When you want normal output, you can exit.
@Nahuel: very nice. However, when you say ls -la | less, for example, long output gets also truncated, since less doesn’t know it’s supposed to output to a terminal. Any idea how to avoid this?
indeed because the tail is done after the command finishes in prompt so program that work with tty can't work interactively to restore output following can be done exec >/dev/stdin ; ls -la | less
note also that some program like ls behaves differently when output is a tty or a file for example with escape sequence, compare touch ''$'\033''[31mhello'$'\033''[0m' and ls *hello* and ls *hello* >/dev/stdin , also ls -a in a tty will display file names in columns whereas in a file will display one file by line like ls -a1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.