Compound command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← What is a Subshell?Homeexec command →

A compound command is one of the following syntax format:

( list )
( command1; command2 )
{ command1; command2 }

Why use ( command1; command2 ) syntax

In the following example, you are running multiple commands:

hostname ; date ; who | wc -l

Now try to save output to a file called /tmp/output.txt:

hostname ; date ; who | wc -l > /tmp/output.txt
cat /tmp/output.txt

All commands will run but only the output of last pipe is saved to the file. To save output of all of the above commands to file, enter:

( hostname ; date ; who | wc -l ) > /tmp/output.txt
cat /tmp/output.txt

All commands inside ( ... ) run using a subshell.

Why use { command1; command2; } syntax

  • This syntax allows you to run all commands in the current shell environment.
  • It works like a group command:
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
← What is a Subshell?Homeexec command →