Monday, February 21, 2022

[SOLVED] What is the difference between ( ... ) and { ... } in bash

Issue

In bash, are there any differences between opting to use ( ... ) or { ... }, as in my test case, both of these product the same expected result:

class="lang-sh prettyprint-override"># using round brackets
(
    echo 'hello'
    echo 'world'
) | rev
# using squiggly brackets
{
    echo 'hello'
    echo 'world'
} | rev
# result:
olleh
dlrow

Perhaps this test case in a condition where they are the same, however are factors where I would opt for one syntax over the other?


Solution

are there any differences between opting to use ( ... ) or { ... }

Yes, one spawns a subshell the other executes commands in current execution environment.

however are factors where I would opt for one syntax over the other?

Sure - use () when you want to spawn a subshell.

In bash, are there any differences between these two code blocks:

(I think, but I'm not 100% sure) that no. The left side of a pipeline is spawned in a subshell. Then Bash detects that (...) is a single only expression on the left side, so Bash optimizes and does not spawn a subshell and just executes the content of the second list of commands and does not spawn a second subshell, so both should result in exactly the same "count of subshell" being spawned. This is an "optimization", the same way ( ( ( ( ( ( echo ) ) ) ) ) ) can be just one subshell.



Answered By - KamilCuk
Answer Checked By - Senaida (WPSolving Volunteer)