3.16. Subshells

Running a shell script launches another instance of the command processor. Just as your commands are interpreted at the command line prompt, similarly does a script batch process a list of commands in a file. Each shell script running is, in effect, a subprocess of the parent shell, the one that gives you the prompt at the console or in an xterm window.

A shell script can also launch subprocesses. These subshells let the script do parallel processing, in effect executing multiple subtasks simultaneously.

Note: Variables in a subshell are not visible outside the block of code in the subshell. These are, in effect, local variables.

Example 3-62. Variable scope in a subshell

#!/bin/bash

echo

outer_variable=Outer

(
inner_variable=Inner
echo "From subshell, \"inner_variable\" = $inner_variable"
echo "From subshell, \"outer\" = $outer_variable"
)

echo

if [ -z $inner_variable ]
then
  echo "inner_variable undefined in main body of shell"
else
  echo "inner_variable defined in main body of shell"
fi

echo "From main body of shell, \"inner_variable\" = $inner_variable"
# $inner_variable will show as uninitialized because
# variables defined in a subshell are "local variables".

echo

exit 0

Example 3-63. Running parallel processes in subshells

	(cat list1 list2 list3 | sort | uniq > list123)
	(cat list4 list5 list6 | sort | uniq > list456)
	# Merges and sorts both sets of lists simultaneously.
	
	wait #Don't execute the next command until subshells finish.
	
	diff list123 list456
	

Note: A command block between curly braces does not launch a subshell.

{ command1; command2; command3; ... }