10 Feb 2026

Unix pipes in bioinformatics: streaming data to reduce memory and storage

Giang Nguyen

Giang Nguyen

Read in Vietnamese
Unix pipes in bioinformatics: streaming data to reduce memory and storage

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.

The problem: intermediate files

A single human genome sequencing run can produce, as a rough order of magnitude:

  • Raw reads: 100+ GB of FASTQ files
  • Alignments: 50-100 GB of BAM files
  • Variants: 1-5 GB of VCF files

A workflow that writes an intermediate file at every step multiplies the storage requirement:

Terminal window
# Traditional approach (❌ Wasteful)
bwa mem reference.fa reads.fastq > aligned.sam # 200 GB intermediate
samtools view -b aligned.sam > aligned.bam # 100 GB intermediate
samtools sort aligned.bam > sorted.bam # 100 GB intermediate
samtools index sorted.bam # Already indexed
# Total disk usage: 400 GB for processing 100 GB of raw data!

The costs are:

  • Storage: intermediate files can be several times the size of the original data
  • Time: writing and reading intermediate files adds I/O
  • Failure: if a step fails midway, the intermediates usually have to be rebuilt
  • Complexity: intermediates have to be tracked and cleaned up

Streaming with pipes

A pipe connects the output of one command to the input of the next, so the data is processed as it is produced:

Terminal window
# 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:

  • only one buffer of data sits in memory at a time
  • no disk I/O for intermediates
  • a failure is reported as soon as it occurs
  • the pipeline reads as a linear sequence of commands
  • only the final outputs are kept

How pipes work under the hood

Understanding the mechanics helps explain when a pipeline is efficient and when it is not.

1. File descriptors in Unix

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).

Terminal window
# Example: cat command
cat myfile.txt # Reads file, writes to stdout (terminal)
cat < myfile.txt # Explicitly redirect stdin from file
cat myfile.txt 1> output.txt # Redirect stdout to file

2. Creating a pipe with the pipe system call

When command1 | command2 is entered, the shell:

  1. Creates a pipe - an unnamed, in-memory buffer that connects two processes
  2. Forks process 1 - creates a copy of the shell running command1
  3. Connects stdout of process 1 to the pipe's write end (file descriptor 1)
  4. Forks process 2 - creates a copy of the shell running command2
  5. Connects stdin of process 2 to the pipe's read end (file descriptor 0)
  6. Executes both processes - they run in parallel

Diagram of a pipe:

[command1] [command2]
| |
stdout (fd 1) stdin (fd 0)
| |
v ^
[================================]
Pipe (kernel buffer)

3. The kernel manages the data flow

The Unix kernel manages the pipe as a FIFO (first-in, first-out) buffer:

  • Write side: command1 writes data to the pipe's write end
  • Pipe buffer: data sits in kernel memory (typically tens of KB to about a MB per pipe)
  • Read side: command2 reads data from the pipe's read end

A few behaviours follow from this:

  1. If the pipe is full: the writing process blocks until space is available
  2. If the pipe is empty: the reading process blocks until data arrives
  3. If the reader closes: the writer receives a SIGPIPE signal (broken pipe)
  4. If the writer closes: the reader gets EOF and can finish processing

This synchronisation is handled by the kernel.

4. Example: tracing a pipe

For the pipeline:

Terminal window
cat genome.fasta | grep ">chr1" | wc -l

Step 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) → Terminal

Step 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 up

5. Why pipes do not load everything into RAM

Without pipes (writing to disk):

command1: Read all data → Write 100GB to disk
↓
Disk (100GB) ← Slow, uses storage
↓
command2: Read 100GB from disk → Process → Write results

With pipes (streaming):

command1: Read chunk → Write chunk to pipe buffer (64KB)
↓
Pipe buffer (kernel memory, reused)
↓
command2: Read chunk → Process → Write chunk to next pipe

Only 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.

A practical example: processing a large FASTQ file

The following is an illustrative example of the difference.

Without pipes

Terminal window
# Step 1: Filter low-quality reads
fastqc 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 reads
wc -l reads_filtered.fastq
# Temporary file: 70 GB on disk
# Step 3: Get sequence length distribution
awk 'NR%4==2 {print length}' reads_filtered.fastq | \
sort -n | uniq -c > length_dist.txt
# Processing reads_filtered.fastq again
# Cleanup
rm reads_filtered.fastq
# Total I/O: Read source (100GB) + Write filtered (70GB) + Read filtered (70GB) = 240GB
# Total disk: 170 GB (100 source + 70 intermediate)

With pipes

Terminal window
# Single streaming pipeline: Filter → Count → Length distribution
fastq_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.

Advanced pipe patterns

1. Parallel processing with GNU Parallel

Process several files at once while piping:

Terminal window
# Process 1000 FASTQ files in parallel
find . -name "*.fastq" | \
parallel --pipe --block 10M \
'fastq_quality_filter -q 20 -p 80 | gzip' > all_filtered.fastq.gz

2. tee: branching a pipeline

tee sends the same stream to more than one destination:

Terminal window
# Simultaneously:
# 1. Count reads
# 2. Filter and output
# 3. Generate statistics
samtools 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 subprocess

3. Named pipes (mkfifo) for complex workflows

For workflows that need several inputs or outputs:

Terminal window
# Create named pipes
mkfifo pipe1 pipe2
# Process A writes to pipe1, reads from pipe2
cat input.txt > pipe1 &
# Process B reads from pipe1, writes to pipe2
sort < pipe1 > pipe2 &
# Main process reads final result
uniq < pipe2
# Cleanup
rm pipe1 pipe2

4. Buffering and back pressure

A slow downstream command can become a bottleneck. buffer adds extra memory to absorb it:

Terminal window
# Without buffer: cat blocks if samtools is slow
cat large.bam | samtools view -c
# With buffer: Extra memory absorbs the blocking
cat large.bam | buffer -m 500M | samtools view -c

buffer 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.

5. Process substitution for multiple outputs

Fan out to several processes from a single input:

Terminal window
# Single BAM file → Multiple statistics simultaneously
samtools 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.bam

Common pitfalls

1. Buffering

Problem: an interactive command may not flush its output in pipe mode.

Terminal window
# This might hang (python buffers output in pipe mode)
python long_script.py | tee output.log

Solution: disable buffering.

Terminal window
# Python: Use -u flag or stdbuf
python -u long_script.py | tee output.log
# Or use stdbuf
stdbuf -oL python long_script.py | tee output.log

2. Error handling

Problem: an error in a middle command can be silent.

Terminal window
# If samtools fails, cat and downstream still succeed!
cat input.bam | samtools view -b - > output.bam 2>/dev/null

Solution: set pipefail so the pipeline fails if any command fails.

Terminal window
# If ANY command fails, the entire pipeline fails
set -o pipefail
cat input.bam | samtools view -b - > output.bam

3. Monitoring progress

Problem: a pipeline prints little while it runs.

Terminal window
# No feedback on progress
cat input.fastq | process_cmd | sort > output.txt

Solution: pv (pipe viewer) shows throughput.

Terminal window
# Shows progress, speed, and ETA
cat input.fastq | pv | process_cmd | sort > output.txt
# Or with file size estimation
pv -N "Reading FASTQ" < input.fastq | process_cmd | \
pv -N "Sorting output" | sort > output.txt

4. Debugging a failing pipeline

Problem: it is not obvious which command failed.

Terminal window
# Unclear where failure occurred
cmd1 | cmd2 | cmd3 | cmd4 failed but which one?

Solution: tee intermediate outputs while debugging.

Terminal window
# Save intermediate outputs while piping
cmd1 | tee /tmp/debug1.txt | \
cmd2 | tee /tmp/debug2.txt | \
cmd3 | tee /tmp/debug3.txt | \
cmd4
# Later, inspect intermediates
cat /tmp/debug1.txt | head
cat /tmp/debug2.txt | head
cat /tmp/debug3.txt | head

Pipes in Nextflow modules

Nextflow 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 pipe in BWA_MEM

The relevant line connects bwa and samtools directly:

Terminal window
bwa mem $args -t $task.cpus $INDEX $reads | samtools $samtools_command $args2 ${reference} --threads $task.cpus -o ${prefix}.${extension} -

What happens:

  1. 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.
  2. The pipe (|) connects that output directly to samtools, so the data streams from bwa to samtools without an intermediate SAM file, and memory stays roughly constant.
  3. 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.

The benefit in this workflow

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 intermediate
samtools sort aligned.sam > sorted.bam # 100+ GB final
rm aligned.sam
  • Storage needed: hundreds of GB
  • Disk I/O: read the input (bwa) + write the SAM + read the SAM (samtools)
  • Time: slower because of the intermediate I/O

With a pipe (the Sarek approach):

bwa mem $INDEX $reads | samtools sort -o sorted.bam -
  • Storage needed: the final output only
  • Disk I/O: read the input + write the final BAM
  • Memory: roughly constant regardless of genome size

Flexibility through arguments

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.

Error handling in Nextflow processes

Nextflow marks a task as failed if any command in the chain fails:

Terminal window
bwa mem ... | samtools sort ... # If either fails, Nextflow catches it

This 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.

Pipes for download, upload and cloud storage

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.

Example 1: download, decompress, process (no temporary files)

Scenario: download a compressed reference genome, decompress it and index it without keeping the compressed file.

Terminal window
# Traditional approach (❌ Wasteful)
wget https://example.com/reference.fasta.gz # Downloads 5GB
gunzip reference.fasta.gz # Decompresses to 15GB
samtools faidx reference.fasta # Index the reference
rm 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 needed

What happens:

  1. wget -O - downloads to stdout rather than to disk
  2. gunzip decompresses the stream as it arrives
  3. samtools faidx /dev/stdin reads from the stream
  4. no intermediate compressed file is stored

Example 2: process, compress, upload to S3 (single pipeline)

Scenario: process sequencing data and upload the compressed results to AWS S3 without creating a local compressed file.

Terminal window
# 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/ # Upload
rm 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 locally

What happens:

  1. bwa mem and samtools sort are chained
  2. gzip compresses the BAM stream
  3. aws s3 cp - uploads from stdin
  4. the data is never fully written to local disk

Example 3: download from S3, decompress, analyse

Scenario: analyse BAM files in S3 without downloading the full uncompressed file.

Terminal window
# Traditional approach (❌ Wasteful)
aws s3 cp s3://my-bucket/sample.bam.gz . # Download 50GB
gunzip sample.bam.gz # Decompress to 150GB
samtools 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 overhead

Example 4: download a tarball, extract, index

Scenario: download an archive of reference sequences, extract and index them in one pipeline.

Terminal window
# Traditional approach (❌ Wasteful)
wget https://example.com/genomes.tar.gz # 10GB download
tar -xzf genomes.tar.gz # Extracts to 50GB
for ref in genomes/*.fasta; do
samtools faidx "$ref"
done
rm -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 files

Streaming a specific file from the tarball:

Terminal window
# Extract specific files from tarball without decompressing entire archive
wget -q -O - https://example.com/genomes.tar.gz | \
tar -xzf - genomes/reference.fasta --to-stdout | \
samtools faidx /dev/stdin

Example 5: process multiple files from S3 with GNU Parallel

Scenario: process several files in S3 in parallel.

Terminal window
# List all BAM files in S3 and process in parallel
aws 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)

Example 6: upload results as they are produced

Scenario: generate analysis results and upload them to S3 incrementally, which can be useful for long-running processes.

Terminal window
# Real-time upload of VCF variants as they're discovered
bcftools 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 continues

A monitoring variant:

Terminal window
# Start a 24-hour variant calling run with real-time uploading
samtools 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"

Tips for reliable download/upload pipes

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

Considerations for cloud pipes

1. Network vs. disk bottleneck

Terminal window
# If network is slower than local processing:
# Download once, process multiple times
wget -O - file.tar.gz | tee local.tar.gz | tar -xz | process1
tar -xz < local.tar.gz | process2
tar -xz < local.tar.gz | process3
# Tradeoff: Local storage vs. network bandwidth

2. Retry logic for failed S3 operations

Terminal window
# Simple retry with exponential backoff
retry_count=0
while [ $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 | process

3. Monitoring upload progress

Terminal window
# Use pv to monitor upload speed
process_data | \
pv -br | \
gzip | \
aws s3 cp - s3://bucket/file.gz
# Output: [1.2GB/s] or similar

4. Multipart upload for large files

For files larger than a few GB, AWS S3 multipart uploads are more reliable:

Terminal window
# 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

Further examples

RNA-seq quality control

Terminal window
# 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

Variant calling

Terminal window
# Align reads, mark duplicates, and call variants in one pass
bwa 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)

FASTA processing with decompression

Terminal window
# Decompress, process, and recompress in a single pipeline
zcat 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

Summary

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

Key points

1. Pipes process data as a stream

  • data flows through memory buffers rather than through intermediate files
  • only a small buffer per pipe sits in memory at a time
  • processing 1 GB or 1 TB uses roughly the same constant memory
  • this is the main difference from a file-based workflow

2. Kernel-level synchronisation is automatic

  • no manual management is needed
  • back pressure prevents a slow command from being overwhelmed
  • if a command fails, set -o pipefail makes the whole pipeline fail

3. The reduction in I/O can be large

  • as an illustration: 100GB reads → 500GB SAM → 100GB BAM with intermediates, versus 100GB reads → 100GB BAM with a pipe
  • the actual figures depend on the tools and the data
  • on disk-bound steps the difference can be noticeable

4. Pipes work with cloud storage

  • download with wget -O - or aws s3 cp - s3://...
  • stream directly from S3 without local copies
  • upload results while processing
  • combine with tee for simultaneous processing and uploading

5. Production workflows use pipes

  • Sarek's BWA_MEM process pipes bwa mem | samtools sort
  • this is a common pattern at larger scales
  • Nextflow adds scheduling and error handling on top
  • pipes and Nextflow are not alternatives; they are used together

6. 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:

  • large datasets where I/O is the bottleneck
  • cloud workflows where local disk is expensive
  • monitoring long-running analyses
  • linear processing chains
  • Nextflow process scripts that chain tools internally

Where pipes are less suitable:

  • highly branching workflows with many paths
  • cases where a failure needs to restart from the middle
  • data that must be read several times
  • cases where intermediate results must be inspected extensively

8. Tools worth knowing

Terminal window
set -o pipefail # Error handling
tee # Branching
pv # Progress monitoring
process substitution: >(cmd) # Streaming to files
AWS S3 pipes: aws s3 cp - s3://... # Cloud integration
GNU parallel # Scale across cores

Final thoughts

Unix 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.

References

Related articles

Browse all articles →