Why the `{cat,filename}` Group command with braces in Linux shell can work?

Viewed 88

Im studying Linux.Now is reading group command.
Group commands in the current shell: { }

{ list; }

More in https://ss64.com/bash/syntax-brackets.html

The semicolon (or newline) following list is required.The braces are reserved words, so they must be separated from the list by blanks.

But When I test in my Ubuntu like {cat,2.txt} and {ls,-l}

highway@ubuntu:~/Desktop$ {cat,2.txt}
This is test2!

highway@ubuntu:~/Desktop$ {ls,-l}
total 12692
-rw-rw-r-- 1 highway highway       15 Jul  2 16:49 2.txt
...

The both command are not separated by blanks and also the semicolon not following the list. But When I follow the quote,shell told me command not found

highway@ubuntu:~/Desktop$ { ls,-l; }
ls,-l: command not found
highway@ubuntu:~/Desktop$ { cat,2.txt; }
cat,2.txt: command not found

In the next test,I find in non-metacharacters only , can success.

highway@ubuntu:~/Desktop$ {cat.2.txt}
{cat.2.txt}: command not found
highway@ubuntu:~/Desktop$ {cat_2.txt}
{cat_2.txt}: command not found
highway@ubuntu:~/Desktop$ {cat#2.txt}
{cat#2.txt}: command not found
highway@ubuntu:~/Desktop$ {cat,2.txt}
This is test2!

So 2 questions I want to know

  1. why {cat,2.txt} can work without following semicolon and no separated by blanks?
    In other words,WHY the command {cat,filename} is parsed correctly by shell?
  2. why in non-metacharacters only , can success?
    In other words,WHY the , is especial?
1 Answers

TL;DR Braces can also introduce brace expansions, which are processed separately.


{cat,ls} is not a command group; it's a brace expansion. The parser can tell the difference because this is a single word beginning with {, not a command with the word { in command position.

The presence of the comma also indicates that this is brace expansion, rather than a single (potential) command name like {cat.2.txt}.

{ cat.2.txt } would be a command group with the command cat.2.txt receiving the argument }; the group itself is not yet closed by a } appearing in command position.

When {cat,ls} expands, it does so to two words, cat and ls, which is then recognized as a command cat and its argument ls.

Related