
Unix pipe (|) nối trực tiếp đầu ra của lệnh này với đầu vào của lệnh kế tiếp. Trong bioinformatics, nơi các tập dữ liệu giải trình tự rất lớn, đây là một cách thực tế để tránh ghi ra các tệp trung gian: dữ liệu chảy qua pipeline thay vì được ghi xuống đĩa rồi đọc lại ở mỗi bước. Bài viết này xem xét vì sao điều đó quan trọng, cách pipe hoạt động bên trong, và nơi mẫu hình tương tự xuất hiện trong các workflow thực tế như Sarek.
Một lần giải trình tự toàn bộ hệ gen người có thể tạo ra, theo bậc độ lớn gần đúng:
Một workflow ghi một tệp trung gian ở mỗi bước sẽ nhân dung lượng lưu trữ lên:
# 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!Các chi phí là:
Một pipe nối đầu ra của lệnh này với đầu vào của lệnh kế tiếp, nên dữ liệu được xử lý ngay khi nó được sinh ra:
# 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!Các lợi ích được báo cáo là:
Hiểu cơ chế giúp giải thích khi nào một pipeline hiệu quả và khi nào không.
Mỗi tiến trình Unix có ba file descriptor chuẩn:
| Descriptor | Tên | Mục đích | Đích mặc định |
|---|---|---|---|
| 0 | stdin | Đầu vào chuẩn | Bàn phím |
| 1 | stdout | Đầu ra chuẩn | Terminal/Màn hình |
| 2 | stderr | Lỗi chuẩn | Terminal/Màn hình |
Mặc định, tiến trình đọc từ stdin (file descriptor 0) và ghi ra 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 fileKhi gõ command1 | command2, shell:
command1command2Sơ đồ một pipe:
[command1] [command2] | | stdout (fd 1) stdin (fd 0) | | v ^ [================================] Pipe (kernel buffer)Kernel Unix quản lý pipe như một bộ đệm FIFO (vào trước, ra trước):
command1 ghi dữ liệu vào đầu ghi của pipecommand2 đọc dữ liệu từ đầu đọc của pipeMột vài hành vi suy ra từ đó:
Việc đồng bộ này do kernel đảm nhiệm.
Với pipeline:
cat genome.fasta | grep ">chr1" | wc -lBước 1: shell tạo pipeline
User types: cat genome.fasta | grep ">chr1" | wc -l ↓Shell creates: - Pipe A (between cat and grep) - Pipe B (between grep and wc)Bước 2: các tiến trình fork và file descriptor được chuyển hướng
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) → TerminalBước 3: dòng thực thi
Pipe A buffer: Pipe B buffer:[data from cat] → [data to grep] → [data to wc] → [count to terminal]Bước 4: đồng bộ bằng back pressure
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 upKhông dùng pipe (ghi xuống đĩa):
command1: Read all data → Write 100GB to disk ↓ Disk (100GB) ← Slow, uses storage ↓command2: Read 100GB from disk → Process → Write resultsDùng pipe (truyền luồng):
command1: Read chunk → Write chunk to pipe buffer (64KB) ↓ Pipe buffer (kernel memory, reused) ↓command2: Read chunk → Process → Write chunk to next pipeMỗi thời điểm chỉ có một lượng nhỏ dữ liệu (một bộ đệm, cỡ 64KB) nằm trong bộ nhớ. Bộ đệm được dùng lại khi dữ liệu chảy qua, nên mức dùng bộ nhớ gần như không đổi bất kể tổng kích thước dữ liệu, thay vì tăng tuyến tính theo nó.
Phần dưới đây là một ví dụ minh hoạ cho sự khác biệt.
# 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)So sánh minh hoạ:
| Chỉ số | Không dùng pipe | Dùng pipe |
|---|---|---|
| Tổng I/O | 240 GB | 100 GB |
| Dung lượng đĩa | 170 GB | 100 GB |
| Thời gian xử lý | Chậm hơn (đọc đĩa nhiều lần) | Nhanh hơn (một lần đọc tuần tự) |
| Dùng bộ nhớ | Truyền luồng OK | Truyền luồng OK |
| Khôi phục lỗi | Chạy lại toàn bộ pipeline | Vấn đề tính nguyên tử của pipeline |
Các con số ở trên là ước lượng theo bậc độ lớn cho ví dụ; con số thực tế phụ thuộc vào công cụ và dữ liệu.
Xử lý nhiều tệp cùng lúc trong khi vẫn pipe:
# Process 1000 FASTQ files in parallelfind . -name "*.fastq" | \ parallel --pipe --block 10M \ 'fastq_quality_filter -q 20 -p 80 | gzip' > all_filtered.fastq.gztee gửi cùng một luồng tới nhiều đích:
# 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 subprocessVới workflow cần nhiều đầu vào hoặc đầu ra:
# 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 pipe2Một lệnh phía sau chậm có thể trở thành nút thắt. buffer thêm bộ nhớ để hấp thụ điều đó:
# 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 hữu ích khi tiến trình phía sau chậm hơn nhiều so với phía trước, khi còn RAM trống, và khi dữ liệu phía trước tốn kém để tạo lại.
Phân nhánh tới nhiều tiến trình từ một đầu vào:
# 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.bamVấn đề: một lệnh tương tác có thể không xả đầu ra ở chế độ pipe.
# This might hang (python buffers output in pipe mode)python long_script.py | tee output.logGiải pháp: tắt đệm dữ liệu.
# Python: Use -u flag or stdbufpython -u long_script.py | tee output.log# Or use stdbufstdbuf -oL python long_script.py | tee output.logVấn đề: lỗi ở một lệnh giữa chuỗi có thể im lặng.
# If samtools fails, cat and downstream still succeed!cat input.bam | samtools view -b - > output.bam 2>/dev/nullGiải pháp: đặt pipefail để pipeline thất bại nếu bất kỳ lệnh nào thất bại.
# If ANY command fails, the entire pipeline failsset -o pipefail
cat input.bam | samtools view -b - > output.bamVấn đề: pipeline in ra rất ít trong khi chạy.
# No feedback on progresscat input.fastq | process_cmd | sort > output.txtGiải pháp: pv (pipe viewer) hiển thị thông lượng.
# 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.txtVấn đề: không rõ lệnh nào đã thất bại.
# Unclear where failure occurredcmd1 | cmd2 | cmd3 | cmd4 failed but which one?Giải pháp: tee các đầu ra trung gian khi gỡ lỗi.
# 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 | headPipeline Nextflow được dựng từ các tiến trình riêng lẻ, và mỗi tiến trình có thể dùng pipe bên trong để nối công cụ. Tiến trình BWA_MEM trong pipeline nf-core Sarek là một ví dụ.
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 """}Dòng liên quan nối trực tiếp bwa và samtools:
bwa mem $args -t $task.cpus $INDEX $reads | samtools $samtools_command $args2 ${reference} --threads $task.cpus -o ${prefix}.${extension} -Điều gì xảy ra:
bwa mem căn chỉnh read vào hệ gen tham chiếu và ghi SAM ra stdout. Với một hệ gen lớn, đây có thể là hàng trăm GB. Nếu không có pipe, nó sẽ được ghi xuống đĩa thành một tệp .sam trung gian.|) nối đầu ra đó trực tiếp vào samtools, nên dữ liệu truyền từ bwa sang samtools mà không có tệp SAM trung gian, và bộ nhớ giữ gần như không đổi.samtools sort/view xử lý luồng, hoặc sắp xếp (khi sort_bam=true) hoặc chuyển định dạng, ghi trực tiếp ra .bam, .cram hoặc .sam và dùng --threads $task.cpus.Với một lần giải trình tự toàn bộ hệ gen người (~100GB read thô), một so sánh minh hoạ:
Không có pipe (giả định):
bwa mem $INDEX $reads > aligned.sam # 500+ GB intermediatesamtools sort aligned.sam > sorted.bam # 100+ GB finalrm aligned.samCó pipe (cách làm của Sarek):
bwa mem $INDEX $reads | samtools sort -o sorted.bam -Tiến trình chuyển giữa đầu ra có sắp xếp và không sắp xếp chỉ bằng một giá trị:
def samtools_command = sort_bam ? 'sort' : 'view'Định dạng đầu ra cũng được chọn lúc chạy:
def extension = args2.contains("--output-fmt cram") ? "cram" : "bam"Do đó cùng một tiến trình có thể xuất BAM, CRAM hoặc SAM trong khi vẫn giữ cùng mẫu hình pipe.
Nextflow đánh dấu một task là thất bại nếu bất kỳ lệnh nào trong chuỗi thất bại:
bwa mem ... | samtools sort ... # If either fails, Nextflow catches itĐiều này rõ ràng hơn một script bash thông thường, nơi lỗi có thể im lặng. Để pipeline dừng khi có bất kỳ lỗi nào, có thể cấu hình shell dùng pipefail:
process { shell = ['/bin/bash', '-euo', 'pipefail'] // -o pipefail catches pipe errors}Điều này đảm bảo rằng nếu bwa thất bại và không tạo ra gì, samtools coi đầu vào rỗng là lỗi thay vì xử lý thành công trên đó một cách im lặng.
Kết hợp công cụ tải lên/tải xuống với xử lý dữ liệu là một cách phổ biến để tránh tệp trung gian, đặc biệt quan trọng khi làm việc với lưu trữ cloud như AWS S3.
Tình huống: tải một hệ gen tham chiếu đã nén, giải nén và đánh index mà không giữ lại tệp nén.
# 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 neededĐiều gì xảy ra:
wget -O - tải về stdout thay vì ghi xuống đĩagunzip giải nén luồng ngay khi nó tớisamtools faidx /dev/stdin đọc từ luồngTình huống: xử lý dữ liệu giải trình tự và tải kết quả đã nén lên AWS S3 mà không tạo tệp nén cục bộ.
# 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 locallyĐiều gì xảy ra:
bwa mem và samtools sort được nối với nhaugzip nén luồng BAMaws s3 cp - tải lên từ stdinTình huống: phân tích các tệp BAM trong S3 mà không tải toàn bộ tệp chưa nén về cục bộ.
# 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 overheadTình huống: tải một kho nén các trình tự tham chiếu, giải nén và đánh index trong một 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 filesTruyền một tệp cụ thể từ 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/stdinTình huống: xử lý nhiều tệp trong S3 song song.
# 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)Tình huống: sinh kết quả phân tích và tải dần lên S3, hữu ích cho các tiến trình chạy dài.
# 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 continuesMột biến thể để theo dõi:
# 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"| Tình huống | Lệnh pipe | Ghi chú |
|---|---|---|
| Tải xuống + giải nén | wget -O - | gunzip | process |
Dùng -O - để xuất ra stdout |
| Tải lên + nén | process | gzip | aws s3 cp - |
Pipe - cho stdin/stdout |
| Tải từ S3 + phân tích | aws s3 cp s3://... - | process |
- đọc từ stdin ra stdout |
| Giải nén tar theo luồng | wget -O - tar.gz | tar -xz -O file |
-O hoặc --to-stdout xuất ra stdout |
| Nhiều tệp S3 | Dùng aws s3 ls + parallel |
Nối với aws s3 cp s3://... - |
| Theo dõi thời gian thực | Dùng tee để phân nhánh |
Tải lên và xử lý cục bộ đồng thời |
| Xử lý lỗi | Kiểm tra mã thoát với set -o pipefail |
Lỗi S3 cần làm pipeline thất bại |
1. Nút thắt mạng so với đĩa
# 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. Logic thử lại cho thao tác S3 thất bại
# 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. Theo dõi tiến độ tải lên
# 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 cho tệp lớn
Với tệp lớn hơn vài GB, multipart upload của AWS S3 đáng tin cậy hơn:
# 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| Vấn đề | Giải pháp bằng pipe |
|---|---|
| Tệp trung gian | Truyền trực tiếp giữa các công cụ |
| Dung lượng đĩa | Không cần lưu trữ tạm |
| Dùng bộ nhớ | Không đổi, độc lập với kích thước dữ liệu |
| Tốc độ xử lý | Một lần đọc tuần tự dữ liệu |
| Khôi phục khi lỗi | Lỗi được báo ngay |
| Dễ đọc mã | Dòng dữ liệu rõ ràng, tuyến tính |
1. Pipe xử lý dữ liệu như một luồng
2. Đồng bộ ở mức kernel là tự động
set -o pipefail làm cả pipeline thất bại3. Mức giảm I/O có thể rất lớn
4. Pipe hoạt động với lưu trữ cloud
wget -O - hoặc aws s3 cp - s3://...tee để vừa xử lý vừa tải lên5. Các workflow thực tế dùng pipe
BWA_MEM của Sarek pipe bwa mem | samtools sort6. Những mẫu hình dùng nhiều nhất
| Mẫu hình | Trường hợp dùng | Lệnh |
|---|---|---|
| Chuỗi đơn giản | Xử lý tuần tự | cmd1 | cmd2 | cmd3 |
| Phân nhánh | Nhiều đầu ra từ một đầu vào | cmd1 | tee >(cmd2) | cmd3 |
| Tải xuống + xử lý | Tệp từ xa không cần lưu trữ | wget -O - url | gunzip | process |
| Tải lên + nén | Trực tiếp lên lưu trữ cloud | process | gzip | aws s3 cp - |
| An toàn lỗi | Bắt lỗi trong pipe | set -o pipefail |
| Xử lý song song | Mở rộng qua nhiều core/máy | input | parallel 'process' |
7. Nơi pipe hữu ích, và nơi không phù hợp
Nơi pipe hữu ích:
Nơi pipe ít phù hợp:
8. Các công cụ nên biết
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 pipe là một cú pháp nhỏ nhưng có ảnh hưởng lớn trong bioinformatics. Với một lệnh, nó giảm bớt mã và tránh một tệp tạm; ở quy mô lớn, nó có thể là khác biệt giữa một pipeline vừa với dung lượng đĩa hiện có và một pipeline thì không, và nó xuất hiện bên trong hầu hết các hệ thống workflow thực tế. Hiểu cách kernel quản lý file descriptor, đệm dữ liệu và áp dụng back pressure là một nền tảng hữu ích để viết những pipeline dễ suy luận hơn.
pipe(7): 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


