-1

I quite don't understand why Bash would not hold the value of myvar in this example.

 echo hello | read myvar && echo $myvar

I would understand if I were running that command as two separate commands, then the scope of the variable would not exist for the second line.

1 Answers1

1

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?

cas
  • 78,579
  • Another way is: echo hello | { read myvar; echo $myvar; } – sceox Apr 25 '22 at 23:24
  • Yeah, but that still doesn't affect the parent process running echo hello. Try running echo $myvar again after that pipeline finishes. The { read myvar; echo $myvar; } group command is run in the sub-shell created by the pipe. See man bash, search for Compound Commands. Also search for Pipelines. – cas Apr 25 '22 at 23:29