سؤال

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.

نصائح أخرى

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}' 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top