0

I'm not sure I understand the meaning of curly braces relevant to grouping. The only thing I can see that is supposed to be different from using regular () is that {} means execute in the current shell rather than a sub-shell. But having tested this, there seems to be some way to format your data inside of {} which is different from regular (). So for example, I tested the following:

$ {who}
bash: {who}: command not found
[john@pc ~]$ 
[john@pc ~]$ {who;}
bash: syntax error near unexpected token `}'
[john@pc ~]$ {who ;}
bash: syntax error near unexpected token `}'
[john@pc ~]$ { who ;}
john    tty1         2022-11-30 14:51

So clearly there is some sort of structure to using {}, but I can't find any resources to explain that to me online or in my book. Can anyone help me understand it.

2
  • 1
    A big part of the difference is that { and } aren't special characters in the same sense that ( and ) are. ( and ) always have some sort of special meaning unless they're quoted or escaped, but { and } can be -- or be part of -- normal shell "words" (command names, arguments, etc). If you run echo {, the { is passed to echo as a normal argument. If you run echo (, you'll get a syntax error because ( cannot be part of a normal argument unless it's quoted or escaped. Nov 30, 2022 at 20:14

1 Answer 1

3

The { } syntax is named a grouping expression.

It is different from subshell ( ) that spawn a new shell.

Note that this syntax need space around { and } and a ; to finish inline expression, like:

{ grep user /etc/passwd | awk '1'; } 

Not needed in multiline expression:

{
    grep user /etc/passwd |
        awk '1'
}

This syntax is a useful way to combine many command to one stream:

{ cmd1; cmd2; cmd3; } | grep ...

Recommended links:


To be not confused with brace expansion like {1..9}

6
  • Is there anything I can search for online to understand this syntax? Like I just saw a post online with someone using: echo {1..10} And then this seems to print numbers 1-10. But like, there feels like I haven't read something on how to use {}. Even the man page for echo doesn't explain {}
    – john smith
    Nov 30, 2022 at 19:01
  • Added link in my response Nov 30, 2022 at 19:03
  • Oh man, that link is a godsend. Thanks!
    – john smith
    Nov 30, 2022 at 19:06
  • 1
    @SottoVoce I believe there must be a semi-colon after the exit 1; Nov 30, 2022 at 21:52
  • @Paul_Pedant Good point, thanks.
    – Sotto Voce
    Nov 30, 2022 at 22:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .