A subshell is a separate shell process created by ( ), pipelines, or command substitution. Variables set inside may not affect the parent.
Parentheses group
cd /tmp
( cd /var; pwd )
pwdcd inside parentheses does not change the outer shell's directory.
Subshell vs current shell
count=0
( count=1 )
echo "outer count=$count"
{ count=1; }
echo "outer count=$count"Braces { } run in the current shell if on the same line with semicolons—subtle syntax rules apply.
Background jobs
sleep 2 &
jobs
wait& runs in background; wait blocks until jobs finish—useful for parallel steps with care.
Important interview questions and answers
- Q: Why ( cd /var ) leaves parent cwd?
A: Subshell has its own working directory discarded on exit. - Q: Background &?
A: Runs command without blocking; returns job id.
Self-check
- What punctuation creates a subshell for cd?
- What command waits for background jobs?
Tip: Use subshells when you need temporary cd without affecting the parent shell.
Interview prep
- ( ) subshell?
Separate process; cd changes do not persist to parent.
- & background?
Runs command without blocking the shell.