0
0
Bash Scriptingscripting~5 mins

Subshells (command grouping) in Bash Scripting

Choose your learning style9 modes available
Introduction
Subshells let you run a group of commands together in a separate shell. This keeps your main shell safe from changes like directory moves or variable updates.
You want to change directories temporarily without affecting your current location.
You need to run multiple commands and capture their combined output.
You want to isolate environment changes so they don't affect the rest of your script.
You want to run commands in parallel or background without mixing their environment.
You want to group commands for clearer script structure.
Syntax
Bash Scripting
( command1; command2; command3 )
Commands inside parentheses run in a new subshell.
Changes inside the subshell, like directory or variable changes, do not affect the parent shell.
Examples
Change to /tmp directory and list files there, but your current directory stays the same after this runs.
Bash Scripting
(cd /tmp; ls)
Run two echo commands in a subshell and save their combined output in a variable.
Bash Scripting
output=$( (echo Hello; echo World) )
Set a variable inside a subshell and print it. The variable won't exist outside the subshell.
Bash Scripting
(VAR=5; echo $VAR)
Sample Program
This script shows your current directory, then runs a subshell that changes to /tmp and prints the directory inside it. After the subshell ends, it prints the original directory again to show it did not change.
Bash Scripting
#!/bin/bash

# Show current directory
pwd

# Run commands in a subshell
(
  cd /tmp
  echo "Inside subshell:"
  pwd
)

# Show current directory again
pwd
OutputSuccess
Important Notes
Use subshells to protect your main shell environment from temporary changes.
Remember that variables set or changed inside a subshell won't affect the parent shell.
Subshells can be slower if used excessively because they start a new shell process.
Summary
Subshells run grouped commands in a separate shell.
They keep changes like directory or variable updates local to the group.
Use them to isolate command effects and keep your script clean.