0

Do someone knows a way to send the stdout of a command both to another command and display it in the shell screen? Note: without using files.

An example (in this case I use wc -l to make it simple )

~> echo "test" | wc -l
1

but I need to have

test
1

I have tried the tee command, expecting it would do it, but it returns the same thing

~> echo "test" | tee | wc -l
1

Any ideas? Thanks

Barooh
  • 3
  • 1

2 Answers2

2

You can use named pipe with tee to do the trick.

create named pipe: mkfifo /tmp/testpipe

use tee to duplicate output to stdout and pipe: echo "test" | tee /tmp/testpipe

Your command will hang at this moment, since nothing is connected to pipe output. You need to run in different shell cat /tmp/testpipe | wc -l

Named pipe is a file, but it will not do neither disk io nor memory buffering.

DukeLion
  • 3,259
  • 1
  • 18
  • 19
  • Thanks @DukeLion, and I have tested it works. You make me discover the named pipes, I will use it in other situations as in this case I must run this into bash script. – Barooh Jun 07 '12 at 10:57
  • No problem, just run `echo "test" | tee /tmp/testpipe` in background, like this `echo "test" | tee /tmp/testpipe &` – DukeLion Jun 07 '12 at 14:43
  • Thanks @DukeLion! For those who just need to duplicate stdout for multiple processes, the `cat` will exit upon end of the first piped output. Therefore, one may wish to put `cat` into a while loop: `while true ; do cat /tmp/testpipe ; done &` – synapse Jun 08 '17 at 12:45
1

It is really clear how you want the output to be formatted. Even, if you use tee the output will be redirected to wc -l. So, you will not see the output of echo.

I can think of a workaround to send both of echo output and wc -l to the terminal by sending one to stdout and stderr using:

$ echo "test" | tee /dev/stderr | wc -l
test
1

This way you will both sent to your terminal via stdout and stderr.

The idea of using named pipes posted by @DukeLion is a nice one also.

Khaled
  • 36,533
  • 8
  • 72
  • 99