-1

This question already has an answer here:

I learned that sudo echo hello > root-owned-file.txt does not work because the redirection does not inherit root privilege, so you need something more like echo hello | sudo tee root-owned-file.txt or echo hello | sudo cp /dev/stdin root-owned-file.txt. However, grep can use --color=tty to add color when redirected to a tty, but not to other destinations. Is redirection totally separate from the subject process, and if so, how does grep 'know' when to omit colors?

My intuition is that there is more to redirection than just channels 1/2/3; my current theory is that grep sends both colored and plain output to several variants of channel 1, and the parent shell selects the correct variant to redirect to the destination based on whether or not the destination is associated with a tty. Alternatively, the parent shell might prepare the destination process/file and send a signal or file descriptor of some kind to the source process; however, this would have implications on the sequential nature of the pipeline, which I had assumed was more strict. For example, the next command in the pipeline might set a flag before yielding a file descriptor, and the source command might depend on that flag's original value, causing a race condition if the pipeline sequence is not strict.

marked as duplicate by Gilles, Jeff Schaller, GAD3R, Anthon, don_crissti Apr 2 '17 at 11:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    "my current theory..." -- Remember Occam's razor. Usually the simplest explanation is the most likely, and in Unix systems the internals actually are quite simple. – ilkkachu Apr 1 '17 at 12:32
  • @ilkkachu Yes, but without a better understanding of Linux internals, it's hard to tell which theory is simpler - unknown unknowns and such. If I understand correctly, what I was missing was that redirections are also stages in the pipeline, which is certainly simpler than my theories, but just hadn't occurred to me. – John P Apr 1 '17 at 23:00
3

grep just uses isatty(3) to determine whether its standard output is a tty. If it is, it uses colour (with tty or auto), otherwise it doesn’t.

  • Thank you, that explains a lot. From superuser.com/questions/932144/…, I see that 'a pipe is not a terminal' - I wasn't thinking of redirections as stages in the pipeline, and I believe that clears it all up. – John P Apr 1 '17 at 22:55

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