Sunday, January 6, 2013

Difference between {} and () in shell scripting


Whenever shell executes a command or shell script, a sub-shell is spawned, which in turn executes the commands.

To group multiple commands, shell uses two types of operators : () and {}

The commands enclosed within () parentheses are executed in a sub-shell.
The commands enclosed within {} curly braces are executed in the current shell only.

Let us demonstrate () with following example

$ pwd
/Users/foo

$ ( cd python ; pwd )
/Users/foo/python

$ pwd
/Users/foo

Working from sub-shell - (), cd changed the working directory to /Users/foo/python.
The parent shell however remained at /Users/foo

Now let us demonstrate {}

$ pwd
/Users/foo

$ { cd python ; pwd ; }
/Users/foo/python

$ pwd
/Users/foo/python

In this case no new shell was spawned.

Note : While using curly braces {}, precede the closing brace with ;. Else you shall face problem like this

${ cd python ; pwd }
> c
> quit
> ;
-bash: syntax error near unexpected token `;'

No comments:

Post a Comment