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?

share|improve this question
up vote 15 down vote accepted

less writes stdout to

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

There is a C function called "isatty" which checks for its output is writing to a tty.

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

something like that

[[ -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'
share|improve this answer
1  
@tfh If STDOUT is not attached to a pipe or a redirection, it's correct that they don't print that STDOUT is attached to a pipe or a redirection. Put all three in a script. Call bash script.sh, bash script.sh | cat, bash script.sh > file, and see what output you get. – hvd 6 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.