echo hello | read str
echo $str
This read
is executed after the pipeline, which means that the output of the echo
gets read into str
- but because it is after a pipe, the contents of str
are now in a subshell that cannot be read by the parent shell.
What happens in to the contents of str
? Does the pipe create a subshell, and then once the content are read into str
, does the parent process kill the child process and str
is erased - or does the contents of str
live on somewhere outside the shell? Like how do we see what is in the subshells? Can we access subshells from the parent shells?
Solution. Pipelines create subshells. Changes in the while loop do not effect the variables in the outer part of the script, as the while loop is run in a subshell.
A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line. Guiding principle #1: Commands executed in Bash receive their standard input from the process that starts them.
< Bash programming. Subshells are one way for a programmer to capture (usually with the intent of processing) the output from a program or script. Commands to be run inside a subshell are enclosed inside single parentheses and preceeded by a dollar sign: DIRCONTENTS=$(ls -l) echo ${DIRCONTENTS}
A pipeline is a sequence of one or more commands separated by one of the control operators ' | ' or ' |& '. The format for a pipeline is. [time [-p]] [!] command1 [ | or |& command2 ] … The output of each command in the pipeline is connected via a pipe to the input of the next command.
The value of ${str}
only exists during the lifetime of the subshell. Whether the left or right side of the pipe will be parent or subshell depends on the specific shell and the shell version.
Bash 4.x has an option shopt -s lastpipe
to run the last command of a pipeline in the parent shell, like ksh93 does by default. The value of $str
will then persist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With