Wierdness using tee: can anyone explain?

Sometimes I want to display the contents of the channel in the middle (isn't it all?).

I generally do it like this (yes, I know there are other, possibly better ways):

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

which outputs

 hello world world hello 

It is beautiful and beautiful in every way.

Except that I really would like to do this without creating a $ terminal variable. You easily say, just replace " tee $terminal " with " tee $(tty) " in the pipe, and there is no need for a variable? Right?

Wrong.

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

exits

 world hello 

In other words, my exit from the middle of the pipe was swallowed.

Now I agree that this is definitely the first problem in the world, but it annoys me, and I would like to know why the second solution does not work.

Is anyone

+6
source share
2 answers

If your system supports it, you can directly access the current terminal using /dev/tty :

 echo hello world | tee /dev/tty | awk '{print $2, $1}' 

(The file is available on Linux and Mac OS X, anyway.)

The tty command returns the name of a file connected to standard inputs, which may not be a terminal. In your pipe, this is a “file” associated with the standard output of the previous command.

+7
source

You can also use tee with process replacement, 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 ; sleep .01 at the end, if necessary.

Or you can use the standard error for the message:

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

Source: https://habr.com/ru/post/945599/


All Articles