Elad Weiss
Elad Weiss

Reputation: 4002

What is the right way to do command grouping in bash

I would like to group few bash instructions after a condition:

First attempt:

$ [[ 0 == 1 ]] && echo 1; echo 2
2

Second attempt:

$ [[ 0 == 1 ]] && (echo 1; echo 2)
$ [[ 0 == 0 ]] && (echo 1; echo 2)
1
2

So the latter is what I want.

Question: This is the 1st time I'm using (...) syntax in bash. Is (...) the right way to go, or does it have some side effects I might be missing?

Upvotes: 16

Views: 8690

Answers (1)

campovski
campovski

Reputation: 3163

Placing commands in () creates a subshell in which the grouped commands are executed. That means that any changes to variables made in subshell, stay in subshell, for example

$ n=5; [[ "$n" == "5" ]] && ( ((n++)); echo $n); echo $n
6
5

Instead you want to group with {} which doesn't invoke a subshell. Then the output would be

$ n=5; [[ "$n" == "5" ]] && { ((n++)); echo $n; }; echo $n
6
6

Also mind the spaces on the inside of {} and semicolons: { ((n++)); echo $n; };.

Upvotes: 17

Related Questions