1

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?

3
  • Related, if not a dupe: unix.stackexchange.com/questions/401020/… unix.stackexchange.com/questions/430050/… Commented Jan 6, 2021 at 19:38
  • 1
    I was going to say what you said in the last paragraph. When a spec say it dose something, it means that it must behave as if it did the something. So yes I believe it is optimisation. However this is not based on any in depth knowledge of bash. It is based on knowledge of other programming languages and compilers. Commented Jan 6, 2021 at 19:46
  • Note also that running a command in a subshell environment doesn't have to involve child processes, they're just the easy way of implementing subshells. Commented Jan 6, 2021 at 21:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.