What are subshells in bash?
Answer
A subshell is a child process created by the current shell. It inherits copies of the parent's variables and environment but any changes to variables or the working directory in the subshell do NOT affect the parent. Subshells are created by: (1) Parentheses grouping: (cd /tmp; ls) — changes directory only inside the subshell. (2) Command substitution: $(command). (3) Pipelines — each command in a pipe runs in a subshell. (4) Backgrounding with &. Check if you're in a subshell: echo $BASH_SUBSHELL (0 = parent, 1+ = subshell depth). This behavior is why source script.sh is needed to have a script's variable assignments affect the current shell.
Previous
How does rsync work and when do you use it?
Next
How do you pass arguments to a shell script?