← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 11 of 12

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:

  1. Subshells
Syntax
bash
( 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

bash
#!/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)"
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
  1. Setting variables inside ( ... ) and expecting them outside, since a subshell has its own variables.
  2. Using cd inside a subshell and expecting it to change the directory of the script.
  3. Expecting exit in a subshell to stop the parent script.
🔒

Chapter Quiz — Complete all 12 topics to unlock

0/12 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.