I read this post:
I understand the answer, but having the option to execute a set of commands through either {} or () makes to create this post.
If the scenario(s) exists: when is mandatory use {} over () - and vice versa - and why?
I read this post:
I understand the answer, but having the option to execute a set of commands through either {} or () makes to create this post.
If the scenario(s) exists: when is mandatory use {} over () - and vice versa - and why?
The difference between both is that () create a subshell. For example, you can try this:
cd $HOME ; ls The output with those commands will list the files and directories you have for the current user.
Now, using subshell, you can try this:
( cd / ; ls ; ) ; ls What we are doing here is creating a subshell (cd / ; ls) for changing the current directory to / and then, list its files and directories. After that, once the subshells ends we list the files of the current directory but this is not the / dir, in this case the current directory is user home folder ($HOME)
Now if you change the () for {} the behavior will be different.
{ cd / ; ls ; } ; ls Here, the output will list the files and dirs in the / directory for both ls commands.
Let's check another example:
( echo Subshell is $BASH_SUBSHELL ; ) ; echo Subshell is $BASH_SUBSHELL Those commands will echo respectively:
Subshell is 1 Subshell is 0 As you can see, using the environment variable $BASH_SUBSHELL you can get the current subshell level you are, so, when you use () the BASH_SUBSHELL changes (you can use nested subshell as you want).
And another more example:
( vartmp=10 ; echo var is $vartmp ; ) ; echo var is $vartmp In this case, the output will be:
var is 10 var is As you can see,in the second line the $vartmp is empty. This is correct, because when a subshell ends with the execution, all variables, functions and some changes (like modifying a environment variable) will get cleared. So, when you want to display the $vartmp after subshells ends, the output will be empty because the variable doesn't exist.
You can try changing the () to {} in those commands to check the different behaviors.
( )create a subshell, not{ }