Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wierdness using tee: can anyone explain?

Tags:

bash

tee

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?

like image 482
hardcode57 Avatar asked May 22 '13 14:05

hardcode57


1 Answers

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.

like image 125
chepner Avatar answered Sep 22 '22 16:09

chepner