Bash Subshells and Grouping
A subshell runs commands in a separate copy of the shell, while a group runs them in the current shell. Changes made in a subshell vanish, and changes made in a group stay.
A variable change is lost in a subshell
The subshell sets the variable to a new value and prints it. Back in the main shell, the variable still holds its old value.
x=outside
(x=inside; echo "inside: $x")
echo "outside: $x"A variable change is kept in a group
The group sets the variable to a new value and prints it. The main shell keeps that new value after the group ends.
x=outside
{ x=inside; echo "inside: $x"; }
echo "outside: $x"A cd inside a subshell does not leak out
The subshell changes folder and writes a file there. The main shell never moved, so the file is found only inside work.
mkdir -p work
(cd work; echo "report" > note.txt)
if [ -f note.txt ]; then echo "note leaked"; else echo "note stayed put"; fi
if [ -f work/note.txt ]; then echo "note is in work"; fiExample
mkdir -p work
count=0
(count=10; cd work; echo "report" > note.txt; echo "subshell count: $count")
{ count=10; echo "group count: $count"; }
echo "final count: $count"
if [ -f work/note.txt ]; then echo "note is in work"; fiKey points
- Subshell ( ): commands run in a copy of the shell.
- Group { }: commands run in the current shell, so changes stay.
- A variable set in a subshell is lost when the subshell ends.
- A variable set in a group is kept after the group ends.
- cd inside a subshell does not move the main shell.
- A group needs a semicolon before the closing brace and spaces around the braces.
In this example, the count starts at zero. The subshell sets it to ten, moves into work, and writes a file there, but its count change vanishes. The group then sets the count to ten, and that change stays. The final line shows the group's value, and the last check confirms the file sits inside work.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
If x is 0 before (x=5) runs, what is x afterwards in the main shell?