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

Subshells

In this page:

  1. Subshells

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)"
🔒

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.