Roger
Roger

Reputation: 8576

Bash - pipe to variable and file

In the simplified example bellow, "anything" is correctly echoed from the $S" variable into "S.gz" file. However, the variable loses its value out of the pipe stream:

echo 'anything' | tee >(read S | gzip >S.gz)
zcat S.gz
echo '$S='"$S"

It echoes:

anything
$S=

The intended output is:

anything
$S=anything

Another way, same unfortunate output:

echo 'anything' | tee >(read S) | gzip >S.gz
zcat S.gz
echo '$S='"$S"

It echoes:

anything
$S=

Any ideas?

Upvotes: 1

Views: 1063

Answers (1)

chepner
chepner

Reputation: 531075

The read has to execute in the current shell; you need to invert your pipeline.

read S < <(echo anything | tee >(gzip - > S.gz))

or, in bash 4.2 or later, use the lastpipe option. (Note that job control must be inactive for lastpipe to take effect. It is off by default in non-interactive shells, and can be turned off in interactive shells with set +m.)

shopt -s lastpipe
echo anything | tee >(gzip - > S.gz) | read S

Upvotes: 2

Related Questions