Subshells
In this page:
Subshells
Wrapping commands in parentheses, ( commands ), runs them in a separate subshell — a child process with its own copy of variables and working directory that doesn't affect the parent shell. Changes made inside, like cd or variable assignments, disappear once the subshell exits. Subshells are useful for isolating side effects, like temporarily changing directory without affecting the rest of the script.
Note: Use (cd some_dir && command) to run a command in a different directory without permanently changing your script's working directory.
Example: Subshells
#!/bin/bash
original_dir=$(pwd)
(
cd /tmp
echo "Inside subshell: $(pwd)"
)
echo "Back in parent shell: $(pwd)"
echo "Still matches original: $([[ $(pwd) == $original_dir ]] && echo yes || echo no)"
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: