Less file1 file2 | cat β€” why does it work

catlesspipe

When I uss less file1 file2 I get both files shown in the "less buffer viewer", but less file1 file2 | cat prints the content of both files appended to stdout. How does less know if it should show the "less buffer viewer" or produce output to stdout for a next command? What mechanism is used for doing this?

Best Answer

less prints text to stdout. stdout goes

  • to a terminal (/dev/tty?) and opens the default buffer viewer
  • through a pipe when piping it to another programm using | (less text | cut -d: -f1)
  • to a file when redirecting it with > (less text > tmp)

There is a C function called "isatty" which checks if the output is going to a tty (less 4.81, main.c, line 112). If so, it uses the buffer viewer otherwise it behaves like cat.

In bash you can use test (see man test)

  • -t FD file descriptor FD is opened on a terminal
  • -p FILE exists and is a named pipe

Example:

[[ -t 1 ]] && \
    echo 'STDOUT is attached to TTY'

[[ -p /dev/stdout ]] && \
    echo 'STDOUT is attached to a pipe'

[[ ! -t 1 && ! -p /dev/stdout ]] && \
    echo 'STDOUT is attached to a redirection'
Related Question