Wednesday, December 14, 2005

Get Scope With Subshells

You can tell the shell to execute a few commands in a subshell by surrounding them with parens:
pwd; ( cd /tmp; pwd }; pwd
You change directories in the subshell, but once you exit that subshell, the original shell hasn't gone anywhere.

This is particularly useful for scripts where you want to go somewhere and do something, temporarily. My scripts are chock-a-block full of code like this:

cvs -Q co modulename
(
cd modulename
make
)
Don't confuse this with curly braces, which group commands in the current
shell:
pwd; { cd /tmp; pwd; }; pwd
The two kinds of grouping are for two different things. Curlies are good when you want to do I/O redirection of groups of commands. Parens are good when you want to insulate a parent shell from a bunch of temporary changes, without having to save and restore context by hand.

0 Comments:

Post a Comment

<< Home