I sometimes want to output the contents of a pipe in the middle (don't we all?).
I generally do it like this (yes, I know there are other, probably better, ways):
terminal=$(tty)
echo hello world |tee $terminal|awk '{print $2, $1}'
which outputs
hello world
world hello
Which is fine and in all respects lovely.
Except that I'd really like to do it without creating the $terminal variable.
Easy, you say, just replace 'tee $terminal
' with 'tee $(tty)
' in the pipe, and no need for a variable? Right?
Wrong.
echo hello world |tee $(tty)|awk '{print $2, $1}'
outputs
world hello
In other words, my output from the middle of the pipe has been swallowed.
Now I accept that this is definitely a first world problem, but it annoys me and I'd like to know why the second solution doesn't work.
Anyone?
If your system supports it, you can access the current terminal directly with /dev/tty
:
echo hello world | tee /dev/tty | awk '{print $2, $1}'
(The file is available in Linux and Mac OS X, at any rate.)
The tty
command returns the name of the file connected to standard input, which may not necessarily be a terminal. In your pipe, it's the "file" associated with the standard output of the preceding command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With