Linux - Grouping commands

June 2017


Braces and brackets


Introduction


Braces and brackets allow you to group of orders.
With braces, the commands are executed by the current shell, whereas with the parentheses are executed by a subshell, also called fork.

Syntax


Implementation by the current shell
{command; command; command;}
Implementation by a subshell
(command; command; command;...)

Notes:
A separator ";" (semicolon) is necessary before the closing bracket if it is on the same line as the last command. This is not the case when using parenthesis.
The separator control be a line feed
The return code from a control block is the last command executed.
  • Uses
    • The grouping of is used primarily to:
    • Redirect a set of commands to (or from) a file
    • Execute all commands in the background
    • Condition the execution of a set of commands

Example


This is an example that I hope will help to better understand the use of braces and parentheses:
#! /bin/bash

echo -e "#############################"
echo -e "# Using braces #"
echo -e "#############################"

echo -e "\ncurrent directory : \c"
pwd
echo -e "Initialization of variable \"v\" :\nv=\"abc\""
v="abc"
echo -e "\nStart environment under braces...\n"
{
echo -e "Re-asign variable \"v\" :\nv=\"123\""
v="123"
echo -e "\nDisplayvariable \"v\" : \c"
echo -e "$v"
echo -e "\nChange directory : "
echo -e "cd /tmp"
cd /tmp
echo -e "\ncurrent directory : \c"
pwd
}
echo -e "\nTerminate environment under braces...\n"

echo -e "\ncurrent directory : \c"
pwd
echo -e "\nDisplayvariable \"v\" : \c"
echo -e "$v"
echo

unset v
cd $HOME

echo -e "press key to continue..."
read key

echo -e "###############################"
echo -e "# Using brackets #"
echo -e "###############################"

echo -e "\ncurrent directory : \c"
pwd
echo -e "Initialization of variable \"v\" :\nv=\"abc\""
v="abc"
echo -e "\nStart environment under brackets ...\n"
(
echo -e "Re-asign variabl \"v\" :\nv=\"123\""
v="123"
echo -e "\nDisplayvariable \"v\" : \c"
echo -e "$v"
echo -e "\nnChange directory : "
echo -e "cd /tmp"
cd /tmp
echo -e "\ncurrent directory : \c"
pwd
)
echo -e "\nTerminate environment under brackets ...\n"

echo -e "\ncurrent directory : \c"
pwd
echo -e "\nDisplayvariable \"v\" : \c"
echo -e "$v"
echo
exit

Related


Published by jak58. Latest update on December 6, 2009 at 06:11 AM by jak58.
This document, titled "Linux - Grouping commands," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).