There are this two names: a subshell and a child-shell.
Yes, a child process will be started by any of this:
sh -c 'echo "Hello"'
( echo "hello" )
echo "$(echo "hello")
echo "hello" | cat
Are all equivalent and share the same name? Do all share the same properties?
POSIX has this definition:
A shell execution environment consists of ….
But the last paragraph of above link has this:
A subshell environment shall be created as a duplicate of the shell environment, except that signal traps that are not being ignored shall be set to the default action.
And specially:
Command substitution, commands that are grouped with parentheses, and asynchronous lists shall be executed in a subshell environment. Additionally, each command of a multi-command pipeline is in a subshell environment; ….
The sh -c 'echo "Hello"'
is not included there, should that be called a subshell also?
Best Answer
A subshell duplicates the existing shell. It has the same variables¹, the same functions, the same options, etc. Under the hood, a subshell is created with the
fork
system call²; the child process goes on to do what is expected of it while the parent waits (e.g.,$(…)
) or goes on with its life (e.g.,… &
) or otherwise does what is expected of it (e.g.,… | …
).sh -c …
does not create a subshell. It launches another program. That program happens to be a shell, but that's just a coincidence. The program may even be a different shell (e.g., if you runsh -c …
from bash, andsh
is dash), i.e., a completely different program that just happens to have significant similarities in its behavior. Under the hood, launching an external command (sh
or any other) calls thefork
system call and then theexecve
system call to replace the shell program in the subprocess by another program (heresh
).¹ Including
$$
, but excluding some shell-specific variables such as bash and mksh'sBASHPID
.² At least, that's the traditional and usual implementation. Shells can optimize the fork away if they can mimic the behavior otherwise.
Relevant man pages: fork(2), execve(2).