4

Are there actions in Bash other than pipes and command substitution that start a new subshell?

Shelley
  • 217
  • 1
  • 3
  • 7
  • A new process, or a new subshell? – Ignacio Vazquez-Abrams Jul 04 '11 at 18:08
  • It seems that command substitution may not always start a new subshell. See [When does command substitution spawn more subshells than the same commands in isolation?](http://stackoverflow.com/q/21331042) for more details. – Caleb Jan 24 '14 at 11:11

2 Answers2

7

Putting a command chain in parens (( ... )) also starts a new subshell.

( cd /tmp ; pwd ) ; pwd
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Each shell script running is, in effect, a subprocess (child process) of the parent shell.

A shell script can itself launch subprocesses. These subshells let the script do parallel processing, in effect executing multiple subtasks simultaneously.

say you have script test.sh. After you run it if you run the command

ps -ef|grep -i test.sh

you will see the it runs with different PID

In general, an external command in a script forks off a subprocess/subshell

Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Subshells and subprocesses are not the same thing. `grep` in the right-hand side of your pipeline is started by a subshell. The left side is not. So if you were to do `cd .. | pwd`, you'd see the directory change. If you did `echo | cd ..; pwd`, you'd not. Also, `cd` is a shell builtin, so it is never a subprocess, but still in a subshell. A subprocess is a fork-exec. Subprocesses running in a subshell behave like a fork-fork-exec. – Larry Nov 12 '20 at 16:38