wierdness using tee: can anyone explain?
Asked Answered
S

2

6

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?

Sycamore answered 22/5, 2013 at 14:28 Comment(1)
+1 for "first world problem" and good question.Cusack
M
7

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.

Mudslinger answered 22/5, 2013 at 14:37 Comment(2)
Tested and works on raspbian, netbsd, CentOS; so it should be good for most use.Cenac
Ah.yes. That makes complete sense. I should have known that.(o//O). (according to wikipedia thats an emoticon for embarrassed). Thanks.Sycamore
A
1

You can also use tee with Process Substitution if supported on your system:

echo hello world | tee  >(awk '{print $2, $1}')

The line sometimes comes too late, so you may need to add ; sleep .01 at the end if needed.

Or you can use the standard error for reporting:

echo hello world | tee >(cat >&2) |  awk '{print $2, $1}' 
Almetaalmighty answered 22/5, 2013 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.