27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 20. Subshells<br />

Running a shell script launches another instance of the command processor. Just as your commands are<br />

interpreted at the command line prompt, similarly does a script batch process a list of commands in a file.<br />

Each shell script running is, in effect, a subprocess of the parent shell, the one that gives you the prompt at the<br />

console or in an xterm window.<br />

A shell script can also launch subprocesses. These subshells let the script do parallel processing, in effect<br />

executing multiple subtasks simultaneously.<br />

Command List in Parentheses<br />

( command1; command2; command3; ... )<br />

A command list embedded between parentheses runs as a subshell.<br />

Variables in a subshell are not visible outside the block of code in the subshell. They are not accessible<br />

to the parent process, to the shell that launched the subshell. These are, in effect, local variables.<br />

Example 20−1. Variable scope in a subshell<br />

#!/bin/bash<br />

# subshell.sh<br />

echo<br />

outer_variable=Outer<br />

(<br />

inner_variable=Inner<br />

echo "From subshell, \"inner_variable\" = $inner_variable"<br />

echo "From subshell, \"outer\" = $outer_variable"<br />

)<br />

echo<br />

if [ −z "$inner_variable" ]<br />

then<br />

echo "inner_variable undefined in main body of shell"<br />

else<br />

echo "inner_variable defined in main body of shell"<br />

fi<br />

echo "From main body of shell, \"inner_variable\" = $inner_variable"<br />

# $inner_variable will show as uninitialized because<br />

# variables defined in a subshell are "local variables".<br />

echo<br />

exit 0<br />

See also Example 32−1.<br />

+<br />

Chapter 20. Subshells 267

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!