Linux - Grouping commands

December 2016


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 :

This document entitled « Linux - Grouping commands » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.