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.

  • 2
    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 at 10:52
up vote 3 down vote accepted

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

Instead:

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.

Example:

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

Output:

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:

#!/bin/bash

shopt -s lastpipe

a=10

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

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

Output:

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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