I seem to misunderstand the Bash rule for creating a subshell. I thought parentheses always creates a subshell, which runs as its own process.
However, this doesn't seem to be the case. In Code Snippet A (below), the second sleep command does not run in a separate shell (as determined by pstree in another terminal). However, in Code Snippet B, the second sleep command does run in a separate shell. The only difference between the snippets is that the second snippet has two commands within the parentheses.
Could somebody please explain the rule for when subshells are created?
CODE SNIPPET A:
sleep 5
(
sleep 5
)
CODE SNIPPET B:
sleep 5
(
x=1
sleep 5
)
forkand child process is created (to execute external commands) by callingfork + exec. But your first para suggests thatfork + execis called for subshell too. What I am getting wrong here? – haccks Apr 03 '18 at 14:19fork+execis not called for the subshell, it's called for the external command. Without any optimization, there's aforkcall for the subshell and another one for the external command. I've added a detailed flow description to my answer. – Gilles 'SO- stop being evil' Apr 03 '18 at 20:37(...)(in base case), there may or may not be a call toexecdepends on whether the subshell has any external command to execute, while in case of executing any external command there must befork + exec. – haccks Apr 04 '18 at 07:02datein a shell? – haccks Apr 04 '18 at 15:23strace -f -e clone,execve,write bash -c 'date'andstrace -f -e clone,execve,write bash -c 'date; true'– Gilles 'SO- stop being evil' Apr 04 '18 at 15:49date. As it is an external command so shell will firstforka new process and then useexec. But is that the case that shell only callexecasdateis the only command to processed by the shell? – haccks Apr 04 '18 at 15:55execdirectly is an optimization. – Gilles 'SO- stop being evil' Apr 04 '18 at 18:26date(nothing around it). – haccks Apr 04 '18 at 18:34