Explain command grouping and its usages in Linux?


Gaming Laptop Series

Sometimes we need to collectively execute commands in Linux and redirect the whole output to a file. To serve this purpose command grouping is used. Many Linux users don’t know what is command grouping in Linux and how to use it.

In this article, we will explain the command grouping in Linux and its usage.

Using parentheses to group commands

Grouping a list of commands within parentheses i.e. () causes them to execute as if they are a single unit. When commands are grouped the redirection can be applied to the entire command list. You need to separate each command using a semi-colon.

For example –

(date; uptime) > test

Now you can view the output stored in the test file by using –

cat test

The output will look something like this –

Grouping commands within parentheses causes a subshell environment to be created. Each of the commands in the group to be executed in that subshell. Since the group of commands executed in a subshell, variable assignments do not remain in effect after the subshell complete.

Using curly braces to group commands

Using curly braces to group commands causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list of commands is required.

In addition to the creation of a subshell, there is a subtle difference between using parentheses and curly braces due to historical reasons. The braces are reserved words, so they must be separated from the command list by blanks or other shell metacharacters. The parentheses are operators, and are recognized as separate tokens by the shell even if they are not separated from the command list by whitespace.

A character that, when unquoted, separates words. A metacharacter is a blank or one of the following characters: ‘|’, ‘&’, ‘;’, ‘(’, ‘)’, ‘<’, or ‘>’.

For example –

{ ls-l; date; uptime; }>test1

Here the output of the given commands will be redirected to the test1 file.

You can use the given command to see the output stored in the test1 file.

cat test1

This will display –

The benefit of using command grouping is that you can redirect the whole output in a single go without command grouping we need to redirect each command output individually to a file.

Conclusion

I hope you understand how to execute commands in groups in Linux. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.