Pipelines and Data Flow
Constructs multi-stage pipelines connecting commands with pipes for data transformation, filtering, and aggregation in a streaming fashion.
Code
#!/usr/bin/env bash
set -euo pipefail
# Count unique IP addresses from a log
grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" /var/log/syslog 2>/dev/null \
| sort \
| uniq -c \
| sort -rn \
| head -10
# Find largest files in a directory
find /var/log -type f -printf "%s %p\n" 2>/dev/null \
| sort -rn \
| head -5 \
| while read -r size path; do
printf "%10d %s\n" "$size" "$path"
done
# Pipeline with tee for branching output
seq 1 100 \
| tee >(grep -c "even" > /dev/stderr) \
| grep -v "0" \
| wc -l
# Named pipes for inter-process communication
fifo="/tmp/myfifo-$$"
mkfifo "$fifo"
( seq 1 10 > "$fifo" ) &
( while read -r num; do
echo "Received: $num"
done < "$fifo"
) &
wait
rm -f "$fifo"
# Complex pipeline for log analysis
cat /var/log/syslog 2>/dev/null \
| grep -E "ERROR|WARN" \
| awk "{print \$1, \$2, \$NF}" \
| sort \
| uniq -c \
| sort -rn \
| head -20 \
| column -tWhat the code does
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to grep, find, seq, mkfifo and rm, chained through 18 pipes so each stage’s output feeds the next.
What to watch for
- The pipeline is 18 stages deep — when it misbehaves, split the pipe and test the stages separately.
Key statements worth quoting
grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" /var/log/syslog 2>/dev/null \
| sort \
| uniq -c \
| sort -rn \
| head -10
| sort -rn \
| head -5 \
| while read -r size path; do
printf "%10d %s\n" "$size" "$path"
| tee >(grep -c "even" > /dev/stderr) \
| grep -v "0" \
| wc -l
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `grep`, `find`, `seq`, `mkfifo`, `rm` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.