How to Use Subshell in Bash: Syntax and Examples
In Bash, a
subshell is created by enclosing commands within parentheses ( ). This runs the commands in a separate shell process, isolating variable changes and effects from the main shell.Syntax
Use parentheses ( ) to create a subshell in Bash. Commands inside run in a separate shell process.
( command1; command2 ): Runs commands in a subshell.- Variables changed inside do not affect the parent shell.
- Useful for grouping commands or isolating side effects.
bash
( command1; command2 )
Example
This example shows how a variable changed inside a subshell does not affect the variable outside it.
bash
count=5 ( count=10 echo "Inside subshell: count=$count" ) echo "Outside subshell: count=$count"
Output
Inside subshell: count=10
Outside subshell: count=5
Common Pitfalls
One common mistake is expecting variable changes inside a subshell to persist outside. Since subshells run separately, changes are lost after it ends.
Also, using curly braces { } instead of parentheses ( ) does not create a subshell but groups commands in the current shell.
bash
# Wrong: changes lost after subshell count=1 ( count=2 ) echo $count # Outputs 1, not 2 # Right: changes persist without subshell count=1 { count=2 } echo $count # Outputs 2
Output
1
2
Quick Reference
| Usage | Description |
|---|---|
| ( commands ) | Run commands in a subshell, isolating changes |
| { commands; } | Group commands in current shell, no isolation |
| Variable changes inside ( ) | Do not affect parent shell |
| Variable changes inside { } | Affect current shell environment |
Key Takeaways
Use parentheses ( ) to run commands in a subshell in Bash.
Changes to variables inside a subshell do not affect the parent shell.
Curly braces { } group commands without creating a subshell.
Subshells are useful to isolate side effects or run commands in parallel.
Remember subshells run in a separate process, so environment changes are temporary.