7.11 Subshells

7.11 Subshells

Sometimes you need to alter the environment in a shell slightly, but don't want a permanent change. You can change and restore a part of the environment (such as the path or working directory) using shell variables, but that is a clumsy way to go about things. The easy way around these kinds of problems is to use a subshell, an entirely new shell process that you can create just for the purpose of running a command or two. The new shell has a copy of the original shell's environment, and when the new shell exits, any changes you made to its shell environment disappear, leaving the initial shell to run as normal.

To use a subshell, put the commands to be executed by the subshell in parentheses. For example, the following line executes the command uglyprogram in uglydir, leaving the original shell intact:

(cd uglydir; uglyprogram)

Here's another example, showing how to add a component to the path that might cause problems as a permanent change:

(PATH=/usr/confusing:$PATH; uglyprogram)

Pipes and background processes work with subshells too. The following example uses tar to make an archive of the entire directory tree within orig and then unpacks the archive into the new directory target, effectively duplicating the files and folders in orig:

tar cf - orig | (cd target; tar xvf -)

Warning?

Double-check this sort of command before you run it, because you want to make sure that the target directory exists and is completely separate from the orig directory.