Reputation: 1205
Consider the following toy example (what I'm really doing is more complicated) where I want to get two pieces of information from the same sequence of commands:
echo 'cats pajamas
hatori hanso
batterang
catwoman
fratstar' > tmp1
answer1=$(grep 'cat' tmp1)
answer2=$(grep 'cat' tmp1 | wc -l)
In essence, I'm looking for a way to only need to run the earlier command(s) in the sequence, in this case grep
, once, while still obtaining exactly the same values stored in variables answer1
and answer2
. I imagine this would work as splitting the pipe (so to speak) to answer1
and to wc -l
, with the output of the latter going to answer2
.
Note that using an intermittent variable or file to store the output of grep
would alter what wc -l
returns. This motivates my choice of this toy example and limits the relevance of this, I think. This question appears related, however it's not clear to me how one would assign the intermediate piece to another variable. I'm currently in bash
, though alternate shells are an option.
Upvotes: 1
Views: 174
Reputation: 531055
Use tee
with a pair of named pipes. (Strictly speaking, you could do this with one pipe and the standard output of grep
itself, but the presentation is simpler with two pipes.)
mkfifo p1 p2
grep cat tmp1 | tee p1 p2 > /dev/null &
answer1=$(cat p1)
answer2=$(wc -l < p2)
tee
splits the output just as you want, writing it to two separate pipes which are read from independently by cat
and wc -l
later.
I assume this is more applicable to your use case than answer1=$(grep 'cat' tmp1)
and answer2=$(echo "$answer1" | wc -l)
.
Upvotes: 2