top | item 16212022

(no title)

goialoq | 8 years ago

If you redirect output, how can the command know the name of the destination?

discuss

order

xxs|8 years ago

Redirecting (in simple terms) is setting a file descriptor. So the file descriptor can be tested if it partakes in the input.

A quote for you [0]: Under normal circumstances every UNIX program has three streams opened for it when it starts up, one for input, one for output, and one for printing diagnostic or error messages. These are typically attached to the user's terminal (see tty(4) but might instead refer to files or other devices, depending on what the parent process chose to set up. (See also the "Redirection" section of sh(1).)

[0]: https://linux.die.net/man/3/stdout

aaronmdjones|8 years ago

fstat(2) on the output file descriptor, stat(2) on the input file name, see if they have the same block device and inode numbers.

Karliss|8 years ago

Somewhat more common use of this is to check if output goes to terminal so that terminal color codes don't get printed to files.

rocqua|8 years ago

Which is really annoying when you want to pipe grep to less, and need to add --color=always to get grep to understand less takes color codes (when using less -R).