9

I was wondering if there is a way to pipe the output of a command and direct it to the stdout. So for example, fortune prints a fortune cookie and also copies it to the clipboard:

$ fortune | tee >(?stdout?) | pbcopy 
"...Unix, MS-DOS, and Windows NT (also known as the Good, the Bad, and
the Ugly)."
(By Matt Welsh)
  • I don't have my OSX at hand, what about fortune | tee $(tty) | pbcopy? – Archemar Mar 30 '16 at 12:24
6

Your assumption:

fortune | tee >(?stdout?) | pbcopy

won't work because the fortune output will be written to standard out twice, so you will double the output to pbcopy.

In OSX (and other systems support /dev/std{out,err,in}), you can check it:

$ echo 1 | tee /dev/stdout | sed 's/1/2/'
2
2

output 2 twice instead of 1 and 2.

You must use other file descriptors, example standard error through /dev/stderr:

$ echo 1 | tee /dev/stderr | sed 's/1/2/'
1
2

or use tty to get the connected pseudo terminal:

$ echo 1 | tee "$(tty)" | sed 's/1/2/'
1
2

With zsh and multios option set, you don't need tee at all:

$ echo 1 >/dev/stderr | sed 's/1/2/'
1
2
  • tee $(tty) Or, y'know, tee /dev/tty – Kenster Mar 30 '16 at 12:59
6

tee always writes to its standard output. If you want to send the data to a command in addition to the terminal where the standard output is already going, just use process substitution with that command. (Note that in spite of starting with >, process substitution does not redirect standard output, the tee command sees it as a parameter.)

fortune | tee >(pbcopy)
0

cuonglm said it all.

Just try:

fortune | tee "$(tty)" | pbcopy

tty should resolve to actual pseudo terminal (like /dev/pts/99) in interactive session (i.e. in terminal), or no a tty in batch, at and daemon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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