๐ Extended Pipelines and Process Substitution
Pipelines chain commands. Process substitution treats command output as files. Together they enable powerful data flows.
๐งญ Pipeline Fundamentals
1 | |
Data flows left to right: - stdout of command1 โ stdin of command2 - stdout of command2 โ stdin of command3
Exit code reflects last command (unless pipefail is set).
๐งช Advanced Pipeline Patterns
Tee โ Branch Output
Save to file AND continue pipeline:
1 | |
Append mode:
1 | |
Combining Stdout and Stderr
1 2 | |
Named Pipes (FIFOs)
Create persistent communication channel:
1 2 3 4 5 6 7 8 9 10 11 12 | |
Named pipes persist until both ends are closed.
๐ง Process Substitution
Syntax
1 2 | |
Practical Examples
Compare sorted outputs:
1 | |
Feed generated data:
1 2 3 | |
Parallel processing:
1 | |
๐งช Complex Pipeline Chains
Multi-Stage Processing
1 2 3 4 5 6 7 | |
Stages: 1. Filter POST requests 2. Extract IP, timestamp, endpoint 3. Sort by timestamp 4. Count unique entries 5. Sort by count 6. Show top 10
Parallel Branches
1 2 3 4 5 | |
Explanation: - Merge header + two files - Sort merged stream - Branch 1: Count lines โ count.txt - Branch 2: Compress โ archive.gz
๐ง Buffering Issues
Pipelines use buffers โ this affects timing:
| Buffer Type | Size | Trigger |
|---|---|---|
| Full | 4-8 KB | Buffer fills |
| Line | N/A | Newline encountered |
| None | 0 | Immediate flush |
Force line buffering:
1 2 3 | |
Or use unbuffer (from expect package):
1 | |
๐งช Performance Optimization
Minimize Pipeline Stages
Each | spawns a subprocess:
1 2 3 4 5 | |
Use Built-ins When Possible
1 2 3 4 5 | |
๐งพ Portability Notes
| Feature | POSIX | Bash | Zsh |
|---|---|---|---|
Basic pipes \| |
โ | โ | โ |
| Process substitution | โ | โ | โ |
|& (combined) |
โ | โ | โ |
Named pipes mkfifo |
โ | โ | โ |
stdbuf |
โ | โ | โ |
๐งพ Summary
- Pipelines chain commands efficiently.
- Use
teeto branch output. - Process substitution treats commands as files.
- Be aware of buffering โ use
stdbufwhen needed. - Minimize subprocesses for performance.
- Prefer built-ins over external commands.
๐ Continue to: Filesystem Operations