
A Unix pipe (|) connects the output of one command directly to the input of the next. In bioinformatics, where sequencing datasets are large, this is a practical way to avoid writing intermediate files: data flows through the pipeline instead of being written to disk and read back at every step. This post looks at why that matters, how pipes work under the hood, and where the same pattern appears in production workflows such as Sarek.
A single human genome sequencing run can produce, as a rough order of magnitude:
A workflow that writes an intermediate file at every step multiplies the storage requirement:
# Traditional approach (❌ Wasteful)bwa mem reference.fa reads.fastq > aligned.sam # 200 GB intermediatesamtools view -b aligned.sam > aligned.bam # 100 GB intermediatesamtools sort aligned.bam > sorted.bam # 100 GB intermediatesamtools index sorted.bam # Already indexed# Total disk usage: 400 GB for processing 100 GB of raw data!The costs are:
A pipe connects the output of one command to the input of the next, so the data is processed as it is produced:
# Pipe approach (✓ Efficient)bwa mem reference.fa reads.fastq | \ samtools view -b - | \ samtools sort -o sorted.bam -samtools index sorted.bam# Total disk usage: 100 GB (original data + final output)# No intermediate files!The reported benefits are:
Understanding the mechanics helps explain when a pipeline is efficient and when it is not.
Every Unix process has three standard file descriptors:
| Descriptor | Name | Purpose | Default Target |
|---|---|---|---|
| 0 | stdin | Standard input | Keyboard |
| 1 | stdout | Standard output | Terminal/Screen |
| 2 | stderr | Standard error | Terminal/Screen |
By default, processes read from stdin (file descriptor 0) and write to stdout (file descriptor 1).
# Example: cat commandcat myfile.txt # Reads file, writes to stdout (terminal)cat < myfile.txt # Explicitly redirect stdin from filecat myfile.txt 1> output.txt # Redirect stdout to fileWhen command1 | command2 is entered, the shell:
command1command2Diagram of a pipe:
[command1] [command2] | | stdout (fd 1) stdin (fd 0) | | v ^ [================================] Pipe (kernel buffer)The Unix kernel manages the pipe as a FIFO (first-in, first-out) buffer:
command1 writes data to the pipe's write endcommand2 reads data from the pipe's read endA few behaviours follow from this:
This synchronisation is handled by the kernel.
For the pipeline:
cat genome.fasta | grep ">chr1" | wc -lStep 1: the shell creates the pipeline
User types: cat genome.fasta | grep ">chr1" | wc -l ↓Shell creates: - Pipe A (between cat and grep) - Pipe B (between grep and wc)Step 2: processes fork and file descriptors redirect
Process: cat genome.fasta stdout (fd 1) → Pipe A write end
Process: grep ">chr1" stdin (fd 0) ← Pipe A read end stdout (fd 1) → Pipe B write end
Process: wc -l stdin (fd 0) ← Pipe B read end stdout (fd 1) → TerminalStep 3: execution flows
Pipe A buffer: Pipe B buffer:[data from cat] → [data to grep] → [data to wc] → [count to terminal]Step 4: back pressure synchronisation
If grep is slow: - Pipe A fills up - cat blocks (can't write) - System automatically waits for grep to catch up
If wc is slow: - Pipe B fills up - grep blocks (can't write) - System waits for wc to catch upWithout pipes (writing to disk):
command1: Read all data → Write 100GB to disk ↓ Disk (100GB) ← Slow, uses storage ↓command2: Read 100GB from disk → Process → Write resultsWith pipes (streaming):
command1: Read chunk → Write chunk to pipe buffer (64KB) ↓ Pipe buffer (kernel memory, reused) ↓command2: Read chunk → Process → Write chunk to next pipeOnly a small amount of data (one buffer, on the order of 64KB) sits in memory at any moment. The buffer is reused as data flows through, so memory use stays roughly constant regardless of the total data size, rather than growing linearly with it.
The following is an illustrative example of the difference.
# Step 1: Filter low-quality readsfastqc reads.fastq --outdir=qc_before/fastq_quality_filter -i reads.fastq -o reads_filtered.fastq -q 20 -p 80# File created: reads_filtered.fastq (70 GB)
# Step 2: Count remaining readswc -l reads_filtered.fastq# Temporary file: 70 GB on disk
# Step 3: Get sequence length distributionawk 'NR%4==2 {print length}' reads_filtered.fastq | \ sort -n | uniq -c > length_dist.txt# Processing reads_filtered.fastq again
# Cleanuprm reads_filtered.fastq
# Total I/O: Read source (100GB) + Write filtered (70GB) + Read filtered (70GB) = 240GB# Total disk: 170 GB (100 source + 70 intermediate)# Single streaming pipeline: Filter → Count → Length distributionfastq_quality_filter -i reads.fastq -q 20 -p 80 | \ tee >(wc -l > read_count.txt) | \ awk 'NR%4==2 {print length}' | \ sort -n | uniq -c > length_dist.txt
# Total I/O: Read source (100GB) = 100GB# Total disk: 100 GB (source + final outputs only)# Memory: ~100MB (pipe buffers)Illustrative comparison:
| Metric | Without Pipes | With Pipes |
|---|---|---|
| Total I/O | 240 GB | 100 GB |
| Disk space | 170 GB | 100 GB |
| Processing time | Slower (multiple reads from disk) | Faster (one sequential read) |
| Memory usage | Streaming OK | Streaming OK |
| Failure recovery | Restart entire pipeline | Pipeline atomicity issues |
The reported figures above are order-of-magnitude estimates for the example; actual numbers depend on the tools and the data.
Process several files at once while piping:
# Process 1000 FASTQ files in parallelfind . -name "*.fastq" | \ parallel --pipe --block 10M \ 'fastq_quality_filter -q 20 -p 80 | gzip' > all_filtered.fastq.gztee sends the same stream to more than one destination:
# Simultaneously:# 1. Count reads# 2. Filter and output# 3. Generate statisticssamtools view input.bam | \ tee >(samtools flagstat /dev/stdin > flagstat.txt) | \ samtools view -b -F 4 | \ samtools sort -o sorted_aligned.bam -
# The >(command) syntax is "process substitution"# It creates a named pipe to a subprocessFor workflows that need several inputs or outputs:
# Create named pipesmkfifo pipe1 pipe2
# Process A writes to pipe1, reads from pipe2cat input.txt > pipe1 &
# Process B reads from pipe1, writes to pipe2sort < pipe1 > pipe2 &
# Main process reads final resultuniq < pipe2
# Cleanuprm pipe1 pipe2A slow downstream command can become a bottleneck. buffer adds extra memory to absorb it:
# Without buffer: cat blocks if samtools is slowcat large.bam | samtools view -c
# With buffer: Extra memory absorbs the blockingcat large.bam | buffer -m 500M | samtools view -cbuffer is useful when the downstream process is much slower than the upstream one, when spare RAM is available, and when the upstream data would be expensive to regenerate.
Fan out to several processes from a single input:
# Single BAM file → Multiple statistics simultaneouslysamtools view input.bam | \ tee >(samtools view -c > read_count.txt) \ >(awk '{print $3}' | sort | uniq -c > chromosome_dist.txt) \ >(awk '{print $4}' | sort -n > position_stats.txt) \ > /dev/null
# All three statistics generated from a single read of input.bamProblem: an interactive command may not flush its output in pipe mode.
# This might hang (python buffers output in pipe mode)python long_script.py | tee output.logSolution: disable buffering.
# Python: Use -u flag or stdbufpython -u long_script.py | tee output.log# Or use stdbufstdbuf -oL python long_script.py | tee output.logProblem: an error in a middle command can be silent.
# If samtools fails, cat and downstream still succeed!cat input.bam | samtools view -b - > output.bam 2>/dev/nullSolution: set pipefail so the pipeline fails if any command fails.
# If ANY command fails, the entire pipeline failsset -o pipefail
cat input.bam | samtools view -b - > output.bamProblem: a pipeline prints little while it runs.
# No feedback on progresscat input.fastq | process_cmd | sort > output.txtSolution: pv (pipe viewer) shows throughput.
# Shows progress, speed, and ETAcat input.fastq | pv | process_cmd | sort > output.txt
# Or with file size estimationpv -N "Reading FASTQ" < input.fastq | process_cmd | \ pv -N "Sorting output" | sort > output.txtProblem: it is not obvious which command failed.
# Unclear where failure occurredcmd1 | cmd2 | cmd3 | cmd4 failed but which one?Solution: tee intermediate outputs while debugging.
# Save intermediate outputs while pipingcmd1 | tee /tmp/debug1.txt | \ cmd2 | tee /tmp/debug2.txt | \ cmd3 | tee /tmp/debug3.txt | \ cmd4
# Later, inspect intermediatescat /tmp/debug1.txt | headcat /tmp/debug2.txt | headcat /tmp/debug3.txt | headNextflow pipelines are built from individual processes, and each process can use pipes internally to chain tools. The BWA_MEM process from the nf-core Sarek pipeline is one example.
process BWA_MEM { tag "$meta.id" label 'process_high'
conda "${moduleDir}/environment.yml" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? 'https://community-cr-prod.seqera.io/docker/registry/v2/blobs/sha256/bf/bf7890f8d4e38a7586581cb7fa13401b7af1582f21d94eef969df4cea852b6da/data' : 'community.wave.seqera.io/library/bwa_htslib_samtools:56c9f8d5201889a4' }"
input: tuple val(meta) , path(reads) tuple val(meta2), path(index) tuple val(meta3), path(fasta) val sort_bam
output: tuple val(meta), path("*.bam") , emit: bam, optional: true tuple val(meta), path("*.cram") , emit: cram, optional: true tuple val(meta), path("*.csi") , emit: csi, optional: true tuple val(meta), path("*.crai") , emit: crai, optional: true path "versions.yml" , emit: versions
when: task.ext.when == null || task.ext.when
script: def args = task.ext.args ?: '' def args2 = task.ext.args2 ?: '' def prefix = task.ext.prefix ?: "${meta.id}" def samtools_command = sort_bam ? 'sort' : 'view' def extension = args2.contains("--output-fmt sam") ? "sam" : args2.contains("--output-fmt cram") ? "cram": sort_bam && args2.contains("-O cram")? "cram": !sort_bam && args2.contains("-C") ? "cram": "bam" def reference = fasta && extension=="cram" ? "--reference ${fasta}" : "" if (!fasta && extension=="cram") error "Fasta reference is required for CRAM output" """ INDEX=`find -L ./ -name "*.amb" | sed 's/\\.amb\$//'`
bwa mem \\ $args \\ -t $task.cpus \\ \$INDEX \\ $reads \\ | samtools $samtools_command $args2 ${reference} --threads $task.cpus -o ${prefix}.${extension} -
cat <<-END_VERSIONS > versions.yml "${task.process}": bwa: \$(echo \$(bwa 2>&1) | sed 's/^.*Version: //; s/Contact:.*\$//') samtools: \$(echo \$(samtools --version 2>&1) | sed 's/^.*samtools //; s/Using.*\$//') END_VERSIONS """
stub: def args2 = task.ext.args2 ?: '' def prefix = task.ext.prefix ?: "${meta.id}" def extension = args2.contains("--output-fmt sam") ? "sam" : args2.contains("--output-fmt cram") ? "cram": sort_bam && args2.contains("-O cram")? "cram": !sort_bam && args2.contains("-C") ? "cram": "bam" """ touch ${prefix}.${extension} touch ${prefix}.csi touch ${prefix}.crai
cat <<-END_VERSIONS > versions.yml "${task.process}": bwa: \$(echo \$(bwa 2>&1) | sed 's/^.*Version: //; s/Contact:.*\$//') samtools: \$(echo \$(samtools --version 2>&1) | sed 's/^.*samtools //; s/Using.*\$//') END_VERSIONS """}The relevant line connects bwa and samtools directly:
bwa mem $args -t $task.cpus $INDEX $reads | samtools $samtools_command $args2 ${reference} --threads $task.cpus -o ${prefix}.${extension} -What happens:
bwa mem aligns reads to the reference genome and outputs SAM to stdout. For a large genome this can be hundreds of GB. Without the pipe, it would be written to disk as an intermediate .sam file.|) connects that output directly to samtools, so the data streams from bwa to samtools without an intermediate SAM file, and memory stays roughly constant.samtools sort/view processes the stream, either sorting it (when sort_bam=true) or converting the format, writing directly to .bam, .cram or .sam and using --threads $task.cpus.For a human whole-genome run (~100GB of raw reads), an illustrative comparison:
Without a pipe (hypothetical):
bwa mem $INDEX $reads > aligned.sam # 500+ GB intermediatesamtools sort aligned.sam > sorted.bam # 100+ GB finalrm aligned.samWith a pipe (the Sarek approach):
bwa mem $INDEX $reads | samtools sort -o sorted.bam -The process switches between sorted and unsorted output with a single value:
def samtools_command = sort_bam ? 'sort' : 'view'The output format is also selected at run time:
def extension = args2.contains("--output-fmt cram") ? "cram" : "bam"The same process can therefore output BAM, CRAM or SAM while keeping the same pipe pattern.
Nextflow marks a task as failed if any command in the chain fails:
bwa mem ... | samtools sort ... # If either fails, Nextflow catches itThis is more explicit than a plain bash script, where errors can be silent. To make a pipeline stop on any error, the shell can be configured to use pipefail:
process { shell = ['/bin/bash', '-euo', 'pipefail'] // -o pipefail catches pipe errors}This ensures that if bwa fails and produces nothing, samtools treats the empty input as an error rather than succeeding on it silently.
Combining download/upload tools with data processing is a common way to avoid intermediate files, which matters when working with cloud storage such as AWS S3.
Scenario: download a compressed reference genome, decompress it and index it without keeping the compressed file.
# Traditional approach (❌ Wasteful)wget https://example.com/reference.fasta.gz # Downloads 5GBgunzip reference.fasta.gz # Decompresses to 15GBsamtools faidx reference.fasta # Index the referencerm reference.fasta # Cleanup takes time# Total disk space needed: 20GB
# Pipe approach (✓ Efficient)wget -q -O - https://example.com/reference.fasta.gz | \ gunzip | \ samtools faidx /dev/stdin# Total disk space needed: 15GB (final reference only)# No temporary files, no cleanup neededWhat happens:
wget -O - downloads to stdout rather than to diskgunzip decompresses the stream as it arrivessamtools faidx /dev/stdin reads from the streamScenario: process sequencing data and upload the compressed results to AWS S3 without creating a local compressed file.
# Traditional approach (❌ Wasteful)bwa mem reference.fa reads.fastq | samtools sort -o aligned.bam -gzip aligned.bam # Creates aligned.bam.gz (100+ GB)aws s3 cp aligned.bam.gz s3://my-bucket/ # Uploadrm aligned.bam.gz # Cleanup# Total disk space: 200+ GB (original BAM + compressed file)
# Pipe approach (✓ Efficient)bwa mem reference.fa reads.fastq | \ samtools sort -b - | \ gzip | \ aws s3 cp - s3://my-bucket/aligned.bam.gz# Total disk space: 0 GB temporary files# Compressed data uploaded directly to S3# Only stores the final index or metadata files locallyWhat happens:
bwa mem and samtools sort are chainedgzip compresses the BAM streamaws s3 cp - uploads from stdinScenario: analyse BAM files in S3 without downloading the full uncompressed file.
# Traditional approach (❌ Wasteful)aws s3 cp s3://my-bucket/sample.bam.gz . # Download 50GBgunzip sample.bam.gz # Decompress to 150GBsamtools flagstat sample.bam # Analyze# Local disk: 200GB, slow downloads
# Pipe approach (✓ Efficient)aws s3 cp s3://my-bucket/sample.bam.gz - | \ gunzip | \ samtools flagstat /dev/stdin# Local disk: 0 GB temporary files# Stream analysis, no storage overheadScenario: download an archive of reference sequences, extract and index them in one pipeline.
# Traditional approach (❌ Wasteful)wget https://example.com/genomes.tar.gz # 10GB downloadtar -xzf genomes.tar.gz # Extracts to 50GBfor ref in genomes/*.fasta; do samtools faidx "$ref"donerm -rf genomes.tar.gz genomes/ # Cleanup# Disk space: 60GB temporary files
# Pipe approach (✓ Efficient)wget -q -O - https://example.com/genomes.tar.gz | \ tar -xz --to-stdout | \ while read -r line; do echo "$line" >> current_genome.fasta if [[ "$line" =~ ^> ]] && [ -s current_genome.fasta ]; then samtools faidx current_genome.fasta fi done# Or more elegantly with GNU tar:wget -q -O - https://example.com/genomes.tar.gz | \ tar -xz -C /dev/shm # Extract to RAM disk (if available)# Disk space: Only final index filesStreaming a specific file from the tarball:
# Extract specific files from tarball without decompressing entire archivewget -q -O - https://example.com/genomes.tar.gz | \ tar -xzf - genomes/reference.fasta --to-stdout | \ samtools faidx /dev/stdinScenario: process several files in S3 in parallel.
# List all BAM files in S3 and process in parallelaws s3 ls s3://my-bucket/bams/ --recursive | awk '{print $4}' | \ parallel --pipe --block 10M \ 'aws s3 cp "s3://my-bucket/{}" - | \ samtools view -b -F 4 | \ samtools sort -o {/.}.sorted.bam -'
# What happens:# 1. List all S3 objects# 2. Process up to N files in parallel# 3. Each file is downloaded and piped directly to samtools# 4. Results written back to disk (or piped to another command)Scenario: generate analysis results and upload them to S3 incrementally, which can be useful for long-running processes.
# Real-time upload of VCF variants as they're discoveredbcftools mpileup -f reference.fa sample.bam | \ bcftools call -m | \ tee >(gzip | aws s3 cp - s3://my-bucket/variants.vcf.gz) | \ grep -v "^#" | \ wc -l
# What happens:# 1. bcftools generates variants# 2. tee splits the stream into two paths:# - First path: gzip and upload to S3 in real-time# - Second path: count total variants# 3. Both operations happen simultaneously from a single bcftools stream# 4. Results available in S3 even while analysis continuesA monitoring variant:
# Start a 24-hour variant calling run with real-time uploadingsamtools mpileup -f ref.fa *.bam | \ bcftools call -m -v 2>/tmp/variants.log | \ tee >(gzip | aws s3 cp - s3://bucket/live-variants.vcf.gz) | \ tail -100 | grep "PASS" > /tmp/latest_variants.txt
# In another terminal, monitor progress:watch -n 10 "wc -l /tmp/latest_variants.txt && aws s3 ls s3://bucket/live-variants.vcf.gz"| Scenario | Pipe Command | Notes |
|---|---|---|
| Download + decompress | wget -O - | gunzip | process |
Use -O - to output to stdout |
| Upload + compress | process | gzip | aws s3 cp - |
Pipe - for stdin/stdout |
| S3 download + analyze | aws s3 cp s3://... - | process |
- reads from stdin to stdout |
| Tar extract streaming | wget -O - tar.gz | tar -xz -O file |
-O or --to-stdout extracts to stdout |
| Multiple S3 files | Use aws s3 ls + parallel |
Chain with aws s3 cp s3://... - |
| Real-time monitoring | Use tee for branching |
Simultaneous upload and local processing |
| Error handling | Check exit codes with set -o pipefail |
S3 errors need to fail the pipeline |
1. Network vs. disk bottleneck
# If network is slower than local processing:# Download once, process multiple timeswget -O - file.tar.gz | tee local.tar.gz | tar -xz | process1tar -xz < local.tar.gz | process2tar -xz < local.tar.gz | process3# Tradeoff: Local storage vs. network bandwidth2. Retry logic for failed S3 operations
# Simple retry with exponential backoffretry_count=0while [ $retry_count -lt 3 ]; do aws s3 cp s3://bucket/file - 2>/dev/null && break retry_count=$((retry_count + 1)) sleep $((2 ** retry_count))done | gunzip | process3. Monitoring upload progress
# Use pv to monitor upload speedprocess_data | \ pv -br | \ gzip | \ aws s3 cp - s3://bucket/file.gz
# Output: [1.2GB/s] or similar4. Multipart upload for large files
For files larger than a few GB, AWS S3 multipart uploads are more reliable:
# aws s3 cp already handles multipart, but for custom control:process_data | \ gzip | \ aws s3 cp - s3://bucket/large-file.gz \ --sse AES256 \ --storage-class GLACIER # Optional: cheaper storage class# Process RNA-seq reads:# 1. Filter low quality# 2. Count valid reads# 3. Extract length distribution# 4. Detect adapters
fastq_quality_filter -i reads.fastq -q 20 -p 80 | \ tee >(wc -l | awk '{print "Valid reads: "$1/4}' > read_count.txt) | \ tee >(awk 'NR%4==2 {print length}' | \ sort -n | uniq -c > length_dist.txt) | \ fastx_collapser -o collapsed.fastq | \ fastx_clipper -a AGATCGGAAGAGC -o trimmed.fastq# Align reads, mark duplicates, and call variants in one passbwa mem -t 8 reference.fa reads.fastq | \ samtools view -b -S - | \ samtools sort -o sorted.bam - && \ samtools markdup sorted.bam marked.bam && \ samtools index marked.bam && \ bcftools mpileup -f reference.fa marked.bam | \ bcftools call -mv -o variants.vcf
# Memory: Constant (~1-2 GB for buffers)# Disk: Only intermediate files marked.bam (necessary for bcftools indexing)# Decompress, process, and recompress in a single pipelinezcat genome.fasta.gz | \ awk '/^>/{if(NR>1)print prev_seq; seq=""; prev_seq=$0; next} {seq=seq $0} END{print prev_seq; print seq}' | \ gzip > processed.fasta.gz
# No intermediate uncompressed files# Entire genome processed with minimal disk space| Problem | Pipe Solution |
|---|---|
| Intermediate files | Stream directly between tools |
| Disk space | No temporary storage needed |
| Memory usage | Constant, independent of data size |
| Processing speed | Single sequential read of data |
| Failure recovery | Failures reported immediately |
| Code readability | Clear, linear data flow |
1. Pipes process data as a stream
2. Kernel-level synchronisation is automatic
set -o pipefail makes the whole pipeline fail3. The reduction in I/O can be large
4. Pipes work with cloud storage
wget -O - or aws s3 cp - s3://...tee for simultaneous processing and uploading5. Production workflows use pipes
BWA_MEM process pipes bwa mem | samtools sort6. Patterns used most often
| Pattern | Use Case | Command |
|---|---|---|
| Simple chain | Sequential processing | cmd1 | cmd2 | cmd3 |
| Branching | Multiple outputs from one input | cmd1 | tee >(cmd2) | cmd3 |
| Download + process | Remote files without storage | wget -O - url | gunzip | process |
| Upload + compress | Direct to cloud storage | process | gzip | aws s3 cp - |
| Error safety | Catch failures in pipes | set -o pipefail |
| Parallel processing | Scale across cores/machines | input | parallel 'process' |
7. Where pipes help, and where they do not
Where pipes help:
Where pipes are less suitable:
8. Tools worth knowing
set -o pipefail # Error handlingtee # Branchingpv # Progress monitoringprocess substitution: >(cmd) # Streaming to filesAWS S3 pipes: aws s3 cp - s3://... # Cloud integrationGNU parallel # Scale across coresUnix pipes are a small syntax with a large effect on bioinformatics. For a single command they reduce code and avoid a temporary file; at scale they can be the difference between a pipeline that fits the available disk and one that does not, and they appear inside most production workflow systems. Understanding how the kernel manages file descriptors, buffers data and applies back pressure is a useful basis for writing pipelines that are easier to reason about.
pipe(7) manual page: man7.org/linux/man-pages/man7/pipe.7.htmlpv (pipe viewer): ivarch.com/programs/pv.shtmls3 cp: docs.aws.amazon.com/cli/latest/reference/s3/cp.html


