Subshells are handy
From FBSD_tips
DRAFT - INCOMPLETE
Contents |
[edit] Rationale
When you are scripting sometimes it is nice to have 2 separate environments, either as a child to your main script or 2 children shells cooperating. A very lightweight way to do this is to create a subshell. This is very convenient compared to putting the commands into their own file and sourcing them through an interpreter.
[edit] Concept
In Bourne shell syntax (valid in bash too) you enclose the commands inside parenthesis that you want to isolate in their own environment.
[edit] Examples
[edit] Demonstration of environment scope
Each subshell inherits it's environment from it's parent. It makes any changes locally to it and propagates that on to any children.
export FOO=outside; echo ${FOO} \
(export FOO=inside; (echo ${FOO}; export FOO=really_inside; echo ${FOO}); echo ${FOO}); \
echo ${FOO}
This should output :
outside inside really_inside inside outside
[edit] Tarring from one place to another
Subshells also have their own current working directories. This will put one child in a source directory and if it exists, run a tar create command. The output is piped to another sub shell that connects to a destination directory and if it exists, runs the complimentary un-tar command.
( cd /path/to/source && tar cf - ) | ( cd /path/to/destination && tar xpvf -)
This achieves a similar effect to tar's -C option.
