tesolat
tesolat

Reputation: 81

Capture bash command output in multiple, independent processes without repetition or use of tmp files

To capture the output of a bash process, we can use redirects or pipes:

fooProcess > output.txt

...or...

fooProcess | barProcess

I'm curious if there is a way to capture the output of fooProcess and re-use it? For example, here's the repetitive approach:

fooProcess | barProcess
fooProcess | bifProcess

...or...

fooProcess > file1.txt
fooProcess > file2.txt

In bash, what's the way to do two independent things with the output of fooProcess without repeating it or storing it some way? Something like:

"Execute fooProcess once and then store all its output in both file1.txt AND file2.txt" or "Execute fooProcess once and then pipe it first to barProcess and then to bifProcess".

Does bash even do this? What's the term for it?

Upvotes: 0

Views: 45

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52152

To write to multiple files, use tee:

cmd | tee file1 file2

To pipe to multiple processes, you can use process substitution and tee:

cmd | tee >(process1) >(process2)

These both still print to standard output. If you don't want that, you have to redirect one more time:

cmd | tee file1 file2 >/dev/null
cmd | tee >(process1) >(process2) >/dev/null

or use redirect to one of the files/processes like this:

cmd | tee file1 > file2
cmd | tee >(process1) | process2

Upvotes: 1

Related Questions