why doesn't value get assigned to variable when it's piped. for example:

a=15|echo $a

Trying to group command's with {} and pass it to pipe, but value initialized in {} can't be used by command after pipe.

  • 3
    Commands on either side of a pipe are executed in separate processes, so variable setting on one won't affect the other. Please provide an example with more context so that we can see what you're trying to accomplish. – muru Jun 29 '18 at 10:52

The command makes little sense as an assignment does not produce any output and echo doesn't read from its standard input.


a=15; printf '%s\n' "$a"

In addition to that, both parts of the pipeline are run in separate environments, so setting a to the left will not affect the value of a on the right of the pipeline.


{ a=15; printf 'on the left:\ta=%s\n' "$a"; } | { cat; printf 'on the right:\ta=%s\n' "$a"; }


on the left:    a=15
on the right:   a=

... assuming a had no value before executing the above. If it had, the right-hand side would have picked up that value. Setting the value in either part of the pipeline would not change the value of a in the surrounding environment.

If the lastpipe shell option had been set and the shell was running without job control (as it would do if it was a non-interactive script), then the last part of the pipe would run in the same environment as the surrounding script. This means that an assignment there would "survive" the pipe:


shopt -s lastpipe


printf 'LHS: a=%s\n' "$a" | { cat; printf 'RHS: a=%s\n' "$a"; a=30; }

printf 'a is now %s\n' "$a"


LHS: a=10
RHS: a=10
a is now 30

Removing shopt -s lastpipe:

LHS: a=10
RHS: a=10
a is now 10

Your example does not make sense, but let me give a better example:

echo foo | read REPLY

is a shell construct that may work (the way you might expect) or not since POSIX does not grant a specific way to set up pipes in a shell.

My example would have foo in $REPLY if you try it with bosh, ksh93 or zsh and would have an empty REPLY on other shells.

This is because bosh, ksh93 and zsh run the rightmost program of a pipeline in the main shell in case it is a shell builtin while other shells always run the rightmost program in a sub-shell that reads the reply and then immediately dies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.