Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash - pipe creates a subshell

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?

like image 367
capser Avatar asked Oct 26 '17 06:10

capser


People also ask

Does pipe create a subshell?

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.

What does bash pipe do?

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.

What is a subshell bash?

< 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}

What is a pipeline in a bash shell?

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.


1 Answers

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.

like image 80
Henk Langeveld Avatar answered Jan 22 '23 07:01

Henk Langeveld