I saw this video which explains that when running a command in parentheses it actually runs the command in a subshell, which is a child process of the original shell. Running the following experiment:
// one shell with PID 5344
~$ (find /)
// another shell
~$ ps l
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
...
0 1000 5344 5333 20 0 10888 5220 do_wai Ss pts/0 0:00 bash
0 1000 5384 5333 20 0 10888 5140 do_wai Ss pts/1 0:00 bash
0 1000 7239 5344 20 0 10860 3444 - R+ pts/0 0:00 find /
4 1000 7240 5384 20 0 11400 3224 - R+ pts/1 0:00 ps l
We can see that find /
is a child of 5344
, with no other shell in between. Wheres running:
// one shell with PID 5344
(cd /; find /)
// second shell
~$ ps l
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
...
0 1000 5344 5333 20 0 10888 5220 do_wai Ss pts/0 0:00 bash
0 1000 5384 5333 20 0 10888 5140 do_wai Ss pts/1 0:00 bash
1 1000 7379 5344 20 0 10888 3036 do_wai S+ pts/0 0:00 bash
4 1000 7380 7379 20 0 10864 3536 - R+ pts/0 0:01 find /
4 1000 7381 5384 20 0 11400 3184 - R+ pts/1 0:00 ps l
Now we can see that other shell in between. My guess is that it is some optimization of bash: In the first case, it doesn't really have to spawn another shell, so it just doesn't do it. In the second case, since the commands include cd /
, which will have affect on the current shell, it has to spawn another process. Is that so?
However this is not based on any in depth knowledge of bash. It is based on knowledge of other programming languages and compilers.
– ctrl-alt-delor Jan 06 '21 at 19:46