Pipe processes run in a sub-shell, and it is impossible for child processes to affect the environment of their parent (and their own environment goes away when the child process terminates). In your example, the read myvar
is run in a sub-shell - myvar is set, but does not (can not) propagate back to the parent shell which runs both echo
statements.
You'll need to use a here string or redirection and process substitution instead of a pipe. For example:
Here string:
$ read myvar <<<"hello" && echo $myvar
hello
The string can be a fixed string or variable(s) or a combination of both:
$ read myvar <<<"Hello $USER, your home is $HOME" && echo $myvar
Hello cas, your home is /home/cas
Redirection and process substitution:
$ read myvar < <(echo hello) && echo $myvar
hello
See also:
Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?
echo hello | { read myvar; echo $myvar; }
– sceox Apr 25 '22 at 23:24echo hello
. Try runningecho $myvar
again after that pipeline finishes. The{ read myvar; echo $myvar; }
group command is run in the sub-shell created by the pipe. Seeman bash
, search for Compound Commands. Also search for Pipelines. – cas Apr 25 '22 at 23:29