Subshells and process substitution

Intermediate · 8 min

Know when Bash quietly runs code in a copy of itself, why variables set there vanish, and how <(command) feeds a command's output to tools that want files.

Before thisPipes and pipelinesVariables and the environmentLoops - for, while and untilReading input and here documentsTraps and cleanup

theurbanpenguin · 8 min

Subshells and process substitution

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by theurbanpenguinReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A subshell is a child copy of the current shell. It sees your variables and working directory, but nothing it changes (variables, `cd`) comes back.
  • `( commands )` runs in a subshell, while `{ commands; }` groups commands in the current shell. Command substitution `$( )`, background jobs and every stage of a pipeline are also subshells.
  • `$$` stays the same inside a subshell, but `$BASHPID` gives the real process ID, so comparing them shows whether you are in one.
  • `<(command)` runs the command and substitutes a file-like path, `/dev/fd/63` in my test, that reads its output. It lets `diff`, `comm` and `wc` take command output where they expect file names.
  • Process substitution is Bash syntax, not POSIX, so it is a syntax error under `sh -c`, and `while read ... done < <(cmd)` is the usual way to avoid the pipeline-subshell trap.

Copies of the shell

Several times in this roadmap a variable set inside a loop or a block “disappeared”. The cause is always the same, and now it gets a name. When Bash needs to run something in the background, or in the middle of a pipeline, or inside $(...), it forks: it makes a copy of itself and runs the code in the copy. That copy is a subshell.

Think of a photocopy of a document. The copy starts identical to the original and you can scribble on it, but the original stays clean. A subshell inherits your variables, functions, and current directory. What it changes stays with it.

Parentheses versus braces

( commands ) explicitly asks for a subshell. { commands; } groups commands but runs them in the current shell. Same body, different results:

$ pwd; (cd logs; pwd); pwd
/work/l38
/work/l38/logs
/work/l38
$ x=1; (x=2; echo "inside subshell: $x"); echo "outside: $x"
inside subshell: 2
outside: 1
$ x=1; { x=2; echo "inside braces: $x"; }; echo "outside: $x"
inside braces: 2
outside: 2

This makes the subshell a feature. (cd somewhere && do_work) runs do_work there and leaves your script where it was, so you never have to cd back. Note the trailing ; and the spaces in braces: { and } are words, not punctuation.

Which constructs are subshells

$$ is the process ID of the main shell, and it doesn’t change inside a subshell. $BASHPID is the real ID of the process running the code:

$ echo "parent: $$ $BASHPID"; (echo "subshell: $$ $BASHPID")
parent: 27740 27740
subshell: 27740 27754
$ echo "$(echo $BASHPID) is not $BASHPID"
27757 is not 27740

Using that, I confirmed the $(...) ran in a subshell too, and its changes don’t escape: y=$(x=2; echo "$x") gave captured 2, while x stayed 1. The full list: ( ), $( ), & (a background job), each stage of a pipeline, and process substitution. Anything that makes a child shell cannot change your variables.

The pipeline trap, again

$ n=0; printf 'a\nb\n' | while read -r l; do n=$((n+1)); done; echo "n=$n after pipe"
n=0 after pipe
$ n=0; while read -r l; do n=$((n+1)); done < <(printf 'a\nb\n'); echo "n=$n after process substitution"
n=2 after process substitution

In the first form, the while is the second stage of the pipeline, so it runs in a subshell and its n is a copy. The second form moves the producer into a process substitution, which makes the producer the subshell and keeps the loop in your shell.

Bash 4.2 and later also offer shopt -s lastpipe, which runs the last stage of a pipeline in the current shell. It worked in my test (n=2 with lastpipe), but only with job control off, which is the default in scripts and needed set +m in my test harness. Process substitution is the more dependable fix, since it doesn’t hinge on a shell option.

Process substitution

Some commands want file names, not streams. diff compares two files, and you can’t pipe two streams into it. You could write each to a temp file and clean up afterwards. Process substitution does that for you. <(command) runs the command and is replaced by a path from which you can read its output.

$ echo <(true)
/dev/fd/63

That is a file descriptor presented as a file name. The command’s output is the file’s content. Here is compare.sh, which compares the status-code mix of two logs:

#!/usr/bin/env bash
# compare: status-code mix of two logs, side by side
codes() { awk '{ print $8 }' "$1" | sort | uniq -c | awk '{ print $2, $1 }'; }
diff <(codes "$1") <(codes "$2")
$ ./compare.sh logs/first.log logs/second.log
1c1
< 200 21
---
> 200 20
5c5
< 404 3
---
> 404 4

The two logs were the first 40 and last 40 lines of the fixture. One request moved from 200 to 404 between them. ShellCheck reported nothing. Other uses I ran: cat <(echo one) <(echo two) printed one then two, and wc -l <(cat logs/first.log) showed /dev/fd/63 as the file name in its output.

The reverse, >(command), gives a path that a command writes to, with the substituted command reading the data. tee >(wc -l > count.txt) < logs/first.log > /dev/null wrote 100 into count.txt, which is one way to send one stream to two consumers.

It is Bash, not POSIX

$ sh -c 'cat <(echo hi)' 2>&1 | head -2
sh: -c: line 0: syntax error near unexpected token `('
$ /bin/bash -c 'cat <(echo hi)'
hi

On macOS, sh is Bash running in POSIX mode, which rejects the syntax. I’d expect dash to reject it as well, but I didn’t test dash. A script with #!/bin/sh shouldn’t use it. The feature also needs the OS to provide /dev/fd (or named pipes), which macOS did here and Linux is documented to do. See the portability lesson.

About the video

theurbanpenguin’s “Understanding Shells: Linux Sub Shells vs Child Shells” is 8 minutes 25 seconds and was published in November 2022. Its description says it compares subshells and child shells, what is and isn’t inherited when a new shell starts, and how to tell which kind you are in. I couldn’t read a transcript. It covers subshells, not process substitution, so that part comes from the text above and from BlueMonkey 4n6’s process-substitution video, linked as the second view. It is in English. Terminology matters here. Some teachers say “subshell” for ( ) and “child shell” for a fresh bash started from the prompt, which receives only exported variables, and the video seems to follow that split, going by its title and description.

Where this fits

The scripting lessons are nearly done. One thing is left: finding out why a script does what it does, with debugging using set -x and ShellCheck.

Check yourself

  1. 01You write `(cd logs; ls)` in a script. Where are you afterwards?

    Back where you started. The parentheses create a subshell, so the `cd` changed only the subshell's working directory. `{ cd logs; ls; }` would have moved the script itself.

  2. 02Why is a counter set inside `cmd | while read ...; do count=$((count+1)); done` still 0 afterwards?

    Each pipeline stage runs in a subshell, so the loop incremented a copy. Using `done < <(cmd)` runs the loop in the current shell, and the counter keeps its value.

  3. 03How do you compare the sorted output of two commands with `diff` without temp files?

    `diff <(cmd1 | sort) <(cmd2 | sort)`. Each `<( )` becomes a path such as `/dev/fd/63` that `diff` opens like a file.

  4. 04How can you tell from inside a script that you are in a subshell?

    Compare `$$` with `$BASHPID`. `$$` keeps the main shell's process ID everywhere, while `$BASHPID` changes in a subshell.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark