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-77. Variable scope in a subshell

   1 #!/bin/bash
   2 
   3 echo
   4 
   5 outer_variable=Outer
   6 
   7 (
   8 inner_variable=Inner
   9 echo "From subshell, \"inner_variable\" = $inner_variable"
  10 echo "From subshell, \"outer\" = $outer_variable"
  11 )
  12 
  13 echo
  14 
  15 if [ -z $inner_variable ]
  16 then
  17   echo "inner_variable undefined in main body of shell"
  18 else
  19   echo "inner_variable defined in main body of shell"
  20 fi
  21 
  22 echo "From main body of shell, \"inner_variable\" = $inner_variable"
  23 # $inner_variable will show as uninitialized because
  24 # variables defined in a subshell are "local variables".
  25 
  26 echo
  27 
  28 exit 0


Example 3-78. Running parallel processes in subshells

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

Note

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

{ command1; command2; command3; ... }