Difference between revisions of "What is a Subshell?"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
Line 13: Line 13:
 
# now call script that will access die() and $WWWJAIL
 
# now call script that will access die() and $WWWJAIL
 
/etc/nixcraft/setupjail -d cyberciti.com</source>
 
/etc/nixcraft/setupjail -d cyberciti.com</source>
 +
* However, environment variables (such as $HOME, $MAIL etc) are passed to subshell.
 +
==Use exec command to avoid subshell==
 +
You can use the [[exec command]] to avoid subshell. The exec command replaces this shell with the specified program. For example,
 +
<source lang="bash">exec command
 +
# redirect the shells stderr to null
 +
exec 2>/dev/null</source>
 +
 
[[Category:Catching signals]][[Category:Commands]]
 
[[Category:Catching signals]][[Category:Commands]]

Revision as of 21:25, 22 September 2009

  • Whenever you run a shell script, it creates a new process called subshell.
  • A Subshell can be used to do parallel processing.
  • If you start another shell on top of your current shell, it can be referred to as a subshell. Type the following command to see subshell value:
echo $BASH_SUBSHELL

OR

echo "Current shell: $BASH_SUBSHELL"; ( echo "Running du in subshell: $BASH_SUBSHELL" ;cd /tmp; du 2>/tmp/error 1>/tmp/output)

Exporting Functions and Variables

A subshell does not inherit a variable's setting. Use the export command to export variables and functions to subshell:

WWWJAIL=/apache.jail
export WWWJAIL
die() { echo "$@"; exit 2; } 
export -f die
# now call script that will access die() and $WWWJAIL
/etc/nixcraft/setupjail -d cyberciti.com
  • However, environment variables (such as $HOME, $MAIL etc) are passed to subshell.

Use exec command to avoid subshell

You can use the exec command to avoid subshell. The exec command replaces this shell with the specified program. For example,

exec command
# redirect the shells stderr to null
exec 2>/dev/null