Process Management
Subshell Isolation
Changes Stay Inside
Parentheses run commands in a subshell. Variable changes inside the subshell do not overwrite the parent shell's variables.
Program
Play the script to compare the value inside a subshell with the value after it exits.
subshell_isolation.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
start=5
value=$start
(
value=$((value + 10))
echo "inside=$value"
)
echo "outside=$value"
#!/usr/bin/env bash
start=7
value=$start
(
value=$((value + 10))
echo "inside=$value"
)
echo "outside=$value"
#!/usr/bin/env bash
start=9
value=$start
(
value=$((value + 10))
echo "inside=$value"
)
echo "outside=$value"
start ← 5
3start=54value=$startvalues this step5startvalue ← 5
3start=54value=$start5(values this step5value5startsubshell value ← 15
5(6 value=$((value + 10))7 echo "inside=$value"values this step15subshell value5valueecho "inside=$value"
6 value=$((value + 10))7 echo "inside=$value"8)outputinside=15values this step15subshell valueecho "outside=$value"
8)9echo "outside=$value"outputoutside=5values this step5value
start ← 7
3start=74value=$startvalues this step7startvalue ← 7
3start=74value=$start5(values this step7value7startsubshell value ← 17
5(6 value=$((value + 10))7 echo "inside=$value"values this step17subshell value7valueecho "inside=$value"
6 value=$((value + 10))7 echo "inside=$value"8)outputinside=17values this step17subshell valueecho "outside=$value"
8)9echo "outside=$value"outputoutside=7values this step7value
start ← 9
3start=94value=$startvalues this step9startvalue ← 9
3start=94value=$start5(values this step9value9startsubshell value ← 19
5(6 value=$((value + 10))7 echo "inside=$value"values this step19subshell value9valueecho "inside=$value"
6 value=$((value + 10))7 echo "inside=$value"8)outputinside=19values this step19subshell valueecho "outside=$value"
8)9echo "outside=$value"outputoutside=9values this step9value
Follow the Subshell
startbegins as5.- The parent shell sets
value=5. - Inside the subshell,
valuebecomes15. - The subshell prints
inside=15. - After the subshell exits, the parent still has
value=5, so it printsoutside=5. | place | value | output | | --- | --- | --- | | parent before subshell | 5 | - | | inside subshell | 15 | inside=15 | | parent after subshell | 5 | outside=5 |
subshell
`( ... )` runs commands in a child shell process.
isolation
Assignments inside the subshell do not change the parent shell.
parent value
After the subshell finishes, the parent `value` is still the original value.
Exercise: subshell_isolation.sh
Reproduce inside=15 and outside=5, then use the pinned start variants 7 and 9 to predict inside=17 outside=7 and inside=19 outside=9.