1

In my book (Sobell's A Practical Guide to Linux, 4e) it is written that

You can use the parentheses control operator to group commands. When you use this technique, the shell creates a copy of itself, called a subshell, for each group. It treats each group of commands as a list and creates a new process to execute each command...

I don't want to interpret this incorrectly so I figured I'd ask here. Does the creation of a subshell necessarily require the use of these () Groups commands, or is this just a way of ensuring that certain commands run in the same subsell?

Let me perhaps ask by example. Suppose I have commands (executables in PATH) a and b. Is there any difference between the following being entered at the command prompt?

  1. a ; b

  2. (a ; b)

  3. (a) ; (b)

muru
  • 72,889
EE18
  • 233
  • 1
  • a & b share the same environment in the parent shell. 2) same as 1 but in a subshell, so a new process (PID) 3) a & b use a different environment
  • – Gilles Quénot Feb 02 '24 at 20:31
  • Understood! So, especially with regard to the difference between 1) and 3), I am correct to conclude that () is the (only?) way to create a new subshell/environment for the commands to run in. It is not enough to separate them in a list. @GillesQuénot – EE18 Feb 02 '24 at 20:32
  • You can also use $(command) to create a subshell from this command substitution. Another 'subshell' is if you do: sh -c command – Gilles Quénot Feb 02 '24 at 20:35
  • Perhaps I have not yet encountered these yet, so thank you for mentioning those! @GillesQuénot One last follow-up if possible: simply using a;b does not create a new shell as we've just discussed, though it does create a couple new processes. Thus is the creation of a new shell/subshell purely relevant as it pertains to the environment in which a given process executes? I don't know too much about Linux/Unix internals, but presumably the virtual "space" for a given process also includes some data from the environment from which it was called and that is where the shell-dependence comes from? – EE18 Feb 02 '24 at 20:40
  • 1
    @GillesQuénot, sh -c ... is not a subshell, but an entirely separate and independent shell. A subshell is a copy of the shell's execution environment, but launching another shell makes no copy. E.g. foo=abc; sh -c 'echo $foo' prints nothing since foo isn't set in the inner shell (assuming it wasn't exported earlier, which is usually wouldn't be). With a subshell, the value of foo be visible within the subshell too. – ilkkachu Feb 02 '24 at 20:48
  • export SUBS=foobar; bash -c 'echo $SUBS' – Gilles Quénot Feb 02 '24 at 21:01
  • @GillesQuénot you’re exporting the variable; ilkkachu’s example doesn’t. – Stephen Kitt Feb 02 '24 at 22:24