Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

What is a subshell, and which constructs create one?

IntermediateConceptArguments, I/O, here-docs, process substitution and subshells
Answer

A subshell is a forked copy of the shell; changes to variables, cd, set options and traps inside it do not affect the parent. Created by:

  • ( commands )
  • command substitution $(...)
  • each part of a pipeline (except the last with lastpipe)
  • background jobs cmd &
  • process substitution <(...)
( cd /tmp && tar -czf /backup/tmp.tgz . )   # parent's directory unchanged
echo "$BASH_SUBSHELL"                       # 0 in parent, 1+ inside subshells

{ commands; } groups without a subshell (note the spaces and the final ;).

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells