bvb
bvb

Reputation: 783

What is the use of enclosing multiple commands in parenthesis in a Unix shell script

There are several ways to run multiple commands at one go. One way is by separating each command with semicolon:

ls;who;banner Hi

Another way is by enclosing multiple commands in parenthesis.

(cd mydir;pwd)

What will happen by enclosing them in parenthesis?

Upvotes: 1

Views: 2209

Answers (1)

Joni
Joni

Reputation: 111369

The parentheses create a subshell. A subshell is a copy of them current shell, which means that state changes such as changing the working directory with cd or setting shell variables or exporting environment variables don't affect the original shell.

In the case here, the cd command changes the working directory, and pwd shows this. When the prompt returns you will still be in the same directory where you were before because cd changed the directory only in the subshell.

Upvotes: 6

Related Questions