Subshells vs the Current Shell ( ( ) vs { } )
In this page:
Variable Changes Inside a Subshell Don't Escape
Because ( ... ) forks a separate copy of the shell, any variable assignments made inside it are lost once the subshell finishes; the parent shell's variables are untouched.
Example: Variable Changes Inside a Subshell Don't Escape
#!/bin/bash
count=1
( count=99; echo "inside subshell: $count" )
echo "outside subshell: $count"
Login to try C/C++/Java/PHP code in the editor
Curly Braces Share the Current Shell
{ commands; } groups commands but runs them in the current shell environment, so variable assignments and cd calls inside persist after the block finishes.
Note: Note the required space after { and the semicolon before } — these are syntax requirements, not style choices.
Example: Curly Braces Share the Current Shell
#!/bin/bash
count=1
{ count=99; echo "inside group: $count"; }
echo "outside group: $count"
Login to try C/C++/Java/PHP code in the editor
Isolating a Directory Change
A subshell is a clean way to temporarily cd somewhere and run a command there without having to remember to cd back afterward; once the subshell exits, the parent's working directory is unaffected.
Example: Isolating a Directory Change
#!/bin/bash
mkdir -p sub_demo
echo "before: $(pwd | xargs basename)"
( cd sub_demo && echo "inside subshell: $(pwd | xargs basename)" )
echo "after: $(pwd | xargs basename)"
rmdir sub_demo
Login to try C/C++/Java/PHP code in the editor
exit Behaves Differently in Each
Calling exit inside ( ... ) only terminates that subshell, letting the parent script continue; calling exit inside { ...; } terminates the entire script since it runs in the same process.
Example: exit Behaves Differently in Each
#!/bin/bash
( echo "in subshell before exit"; exit 1; echo "never printed" )
echo "script continues after the subshell exited, status was $?"
Login to try C/C++/Java/PHP code in the editor
- Assuming
( ... )and{ ...; }are just stylistic alternatives; they have fundamentally different scoping behavior. - Forgetting that
{ ...; }requires a space after{, a semicolon (or newline) before}, while( ... )needs neither. - Using a subshell for something that must affect the calling script's state, like
cdor exporting a variable, and being confused when the change disappears.
( commands )runs in a subshell: a forked copy of the shell with its own variables, working directory, and traps.{ commands; }runs in the current shell: variable changes,cd, andexitall affect the calling shell directly.- A subshell is useful for isolating side effects, such as temporarily changing directory without affecting the rest of the script.
exitinside( ... )only ends the subshell, not the whole script;exitinside{ ...; }ends the entire script.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: