Skip to content

Subshells & Jobs

Process Substitution

Process substitution allows redirecting the input/output of a command to/from a temporary file descriptor. It uses <() for input redirection and >() for output redirection, which are distinct from standard input/output redirection operators < and >.

Example: Comparing Outputs

$ diff <(echo "hello") <(echo "world")
1c1
< hello
---
> world
This compares the outputs of two commands without temporary files.

Example: Feeding Output to a Command

$ grep "pattern" <(sort file.txt)
The sorted contents of file.txt are fed into grep via process substitution.

Syntax:
- <(): Redirects input from a command.
- >(): Redirects output to a command.

Subshell Creation with ( )

Subshells are created using parentheses () and execute in a separate process context. This isolates variable changes and command execution from the parent shell.

Syntax and Behavior

  • (cmd): Runs cmd in a subshell.
  • Variables modified inside the subshell do not affect the parent shell.

Example: Isolated Variable Modification

$ var="original"
$ (var="subshell"; echo "$var")
subshell
$ echo "$var"
original
The var value in the parent shell remains unchanged.

Background Execution with &

Background execution runs a command asynchronously, freeing the shell for other tasks. Append & to the command to launch it in the background.

Syntax and Behavior

  • cmd &: Executes cmd in the background.
  • Use jobs to monitor active background processes.

Example: Running a Command in the Background

$ sleep 5 &
[1] 12345
$ echo "Continuing execution..."
Continuing execution...
[1]+  Done                    sleep 5
The sleep 5 command runs asynchronously, allowing the shell to process subsequent commands.