Subshells
A subshell is like letting a friend work on a photocopy of your desk. They can rearrange all they want, but your real desk stays exactly as you left it.
In this page:
Syntax
( commands )
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Setting variables inside
( ... )and expecting them outside, since a subshell has its own variables. - Using
cdinside a subshell and expecting it to change the directory of the script. - Expecting
exitin a subshell to stop the parent script.
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: