Most data pipelines don't need Airflow — they need dependency tracking, error isolation, and reproducible execution. This lesson teaches you to build production-grade multi-step transformation pipelines using Makefile and shell scripts, with real code for extraction, validation, logging, and partial re-runs.

You're a data engineer at a mid-sized company. The pipeline you're responsible for pulls sales data from a Postgres database, normalizes it, joins it with customer dimension tables, runs a series of validation checks, and writes Parquet files to S3. The whole thing runs nightly. Your manager asks why you haven't set up Airflow yet.
Here's the honest answer: Airflow is a serious tool that solves serious problems — but it also brings serious overhead. You need a scheduler worker, a metadata database, a web server, potentially Celery or Kubernetes executors, and a team that knows how to operate all of it. For a pipeline that runs once a night and touches five steps, that overhead is enormous. What if you could get 80% of the orchestration benefits — dependency tracking, step-by-step execution, failure isolation, and reproducibility — using tools that are already installed on your machine?
That's exactly what Makefile and shell scripting give you. By the end of this lesson, you'll have a complete, production-grade multi-step transformation pipeline that handles dependency resolution, partial re-runs, structured logging, error handling, and environment parameterization — without deploying a single additional service. This isn't about avoiding real orchestration forever; it's about understanding the right tool for the job and being dangerous when the job doesn't warrant a full framework.
What you'll learn:
You should be comfortable working in a Unix-like terminal (Linux or macOS). You don't need to be a shell expert, but you should understand basic concepts like exit codes, pipes, and environment variables. Familiarity with the fundamentals of data pipeline architecture is assumed — we won't stop to explain what a transformation step is. Some exposure to Python-based pipeline work is helpful; if you haven't yet, check out building your first data pipeline with Python for context on what we're orchestrating.
Make was invented in 1976 to build software. The core idea: a target depends on prerequisites, and if any prerequisite is newer than the target, the recipe for the target runs. This is a dependency graph. It is also, structurally, what every data pipeline DAG describes.
Think about what this means for data pipelines:
Make tracks these relationships by comparing file modification timestamps. If nothing changed, it skips the step. This is exactly the kind of pipeline caching behavior you'd want to implement manually in any other system — and Make gives it to you for free.
Here's the basic anatomy of a Makefile:
target: prerequisite1 prerequisite2
recipe_command_line_1
recipe_command_line_2
Warning
Every recipe line in a Makefile must be indented with a real tab character, not spaces. This is the single most common source of frustration for new Makefile users. If you're using VS Code, install the Makefile Tools extension; it will highlight tab vs. space errors visually.
Each recipe line runs in its own subshell by default, which has important implications we'll address. Let's build something real.
We'll build a nightly pipeline that processes e-commerce order data. Here's what it does:
The directory structure looks like this:
pipeline/
├── Makefile
├── config/
│ ├── env.sh # Environment variables (non-secret)
│ └── pipeline.conf # Pipeline-specific settings
├── scripts/
│ ├── extract.sh
│ ├── clean.py
│ ├── enrich.py
│ ├── validate.py
│ └── load.sh
├── data/
│ ├── raw/
│ ├── cleaned/
│ ├── enriched/
│ └── validated/
└── logs/
Note
We're mixing shell scripts and Python scripts intentionally. Shell excels at orchestration, file movement, and calling external tools. Python excels at data manipulation. Your Makefile will call both — this is the right division of labor.
Before writing targets, establish some conventions at the top of your Makefile:
# Use bash explicitly — not sh — for consistent behavior
SHELL := /bin/bash
# Stop on first error in a recipe
.SHELLFLAGS := -eu -o pipefail -c
# Treat these targets as always-needing-to-run (not file outputs)
.PHONY: all clean extract transform validate load help
# Load environment config
include config/env.sh
export
# Timestamp for log files
TIMESTAMP := $(shell date +%Y%m%d_%H%M%S)
LOG_DIR := logs/$(TIMESTAMP)
# Data directories
RAW_DIR := data/raw
CLEANED_DIR := data/cleaned
ENRICHED_DIR := data/enriched
VALIDATED_DIR := data/validated
The -eu -o pipefail flags on SHELLFLAGS deserve explanation:
-e: Exit immediately if any command fails-u: Treat unset variables as errors-o pipefail: If any command in a pipe fails, the whole pipe fails (not just the last command)This is critical for data pipelines. Without -o pipefail, the command extract_data | gzip > output.gz would succeed even if extract_data crashed — because gzip wrote a valid (but empty) file. That kind of silent failure is the most dangerous kind.
Here's the heart of the Makefile — the targets that model our pipeline DAG:
# Default target — run the full pipeline
all: $(VALIDATED_DIR)/orders_$(DATE).parquet
# STEP 1: Extract
$(RAW_DIR)/orders_$(DATE).csv: | $(RAW_DIR) $(LOG_DIR)
@echo "[$(shell date)] Starting extraction..." | tee -a $(LOG_DIR)/pipeline.log
bash scripts/extract.sh \
--date "$(DATE)" \
--output "$@" \
2>&1 | tee -a $(LOG_DIR)/extract.log
@echo "[$(shell date)] Extraction complete: $@" | tee -a $(LOG_DIR)/pipeline.log
# STEP 2: Clean
$(CLEANED_DIR)/orders_$(DATE).csv: $(RAW_DIR)/orders_$(DATE).csv | $(CLEANED_DIR)
@echo "[$(shell date)] Starting cleaning..." | tee -a $(LOG_DIR)/pipeline.log
python scripts/clean.py \
--input "$<" \
--output "$@" \
2>&1 | tee -a $(LOG_DIR)/clean.log
@echo "[$(shell date)] Cleaning complete: $@" | tee -a $(LOG_DIR)/pipeline.log
# STEP 3: Enrich
$(ENRICHED_DIR)/orders_$(DATE).csv: \
$(CLEANED_DIR)/orders_$(DATE).csv \
$(CLEANED_DIR)/customers_latest.csv \
| $(ENRICHED_DIR)
@echo "[$(shell date)] Starting enrichment..." | tee -a $(LOG_DIR)/pipeline.log
python scripts/enrich.py \
--orders "$<" \
--customers "$(CLEANED_DIR)/customers_latest.csv" \
--output "$@" \
2>&1 | tee -a $(LOG_DIR)/enrich.log
@echo "[$(shell date)] Enrichment complete: $@" | tee -a $(LOG_DIR)/pipeline.log
# STEP 4: Validate
$(VALIDATED_DIR)/orders_$(DATE).parquet: $(ENRICHED_DIR)/orders_$(DATE).csv | $(VALIDATED_DIR)
@echo "[$(shell date)] Starting validation and load..." | tee -a $(LOG_DIR)/pipeline.log
python scripts/validate.py \
--input "$<" \
--output "$@" \
--rules config/validation_rules.yaml \
2>&1 | tee -a $(LOG_DIR)/validate.log
@echo "[$(shell date)] Validation complete: $@" | tee -a $(LOG_DIR)/pipeline.log
# Directory creation (order-only prerequisites use |)
$(RAW_DIR) $(CLEANED_DIR) $(ENRICHED_DIR) $(VALIDATED_DIR) $(LOG_DIR):
mkdir -p $@
There's a lot happening here. Let's unpack the most important ideas:
Automatic variables. $@ means "this target's filename." $< means "the first prerequisite." $^ means "all prerequisites." Using these instead of hardcoded paths makes your targets resilient to rename.
Order-only prerequisites. The | $(RAW_DIR) syntax means "create this directory if it doesn't exist, but don't trigger a rebuild just because the directory's timestamp changed." Without this, adding any file to data/raw/ would re-trigger your extract step.
Chained dependency resolution. When you run make all, Make looks at the final target (orders_$(DATE).parquet), sees it depends on the enriched CSV, which depends on the cleaned CSV, which depends on the raw CSV, and builds them in that order — only running steps where the output is missing or stale.
Key insight
The DATE variable is the linchpin of this whole system. If you run make DATE=2024-01-15, Make will build exactly the pipeline for that date, tracking files like orders_2024-01-15.csv through each stage. This gives you natural incremental loading behavior without any extra bookkeeping.
Your Makefile calls scripts — it doesn't contain the logic itself. Here's scripts/extract.sh:
#!/usr/bin/env bash
set -euo pipefail
# Parse arguments
DATE=""
OUTPUT=""
while [[ $# -gt 0 ]]; do
case $1 in
--date) DATE="$2"; shift 2 ;;
--output) OUTPUT="$2"; shift 2 ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
[[ -z "$DATE" ]] && { echo "ERROR: --date is required" >&2; exit 1; }
[[ -z "$OUTPUT" ]] && { echo "ERROR: --output is required" >&2; exit 1; }
# Validate date format
if ! date -d "$DATE" >/dev/null 2>&1; then
echo "ERROR: Invalid date format: $DATE" >&2
exit 1
fi
echo "Extracting orders for $DATE from ${DB_HOST:-localhost}..."
# Write to a temp file first, rename on success
TEMP_OUTPUT="${OUTPUT}.tmp"
psql \
--host="${DB_HOST}" \
--port="${DB_PORT:-5432}" \
--username="${DB_USER}" \
--dbname="${DB_NAME}" \
--no-password \
--csv \
--command "
SELECT
order_id,
customer_id,
order_date,
total_amount,
status,
shipping_address,
created_at
FROM orders
WHERE order_date::date = '${DATE}'::date
AND deleted_at IS NULL
ORDER BY order_id
" > "$TEMP_OUTPUT"
ROW_COUNT=$(wc -l < "$TEMP_OUTPUT")
echo "Extracted $((ROW_COUNT - 1)) rows (excluding header)"
# Fail fast if we got suspiciously few rows
MIN_ROWS="${MIN_EXPECTED_ROWS:-100}"
if [[ $((ROW_COUNT - 1)) -lt $MIN_ROWS ]]; then
echo "ERROR: Only extracted $((ROW_COUNT - 1)) rows, expected at least $MIN_ROWS" >&2
rm -f "$TEMP_OUTPUT"
exit 1
fi
# Atomic rename — prevents downstream steps from reading partial files
mv "$TEMP_OUTPUT" "$OUTPUT"
echo "Written to $OUTPUT"
Notice the atomic write pattern: write to a temp file, validate, then rename. This is essential for correctness — if your extract crashes midway, you don't want the cleaning step to pick up a half-written file and "succeed" on garbage data. This aligns with idempotent pipeline design principles where each step either completes fully or leaves no artifacts.
Your config/env.sh holds non-secret configuration. Notice that secrets aren't here — they come from environment variables set elsewhere (a secrets manager, Docker secrets, CI/CD environment variables):
# config/env.sh
# Source this file, don't run it
export PIPELINE_ENV="${PIPELINE_ENV:-development}"
export DB_HOST="${DB_HOST:-localhost}"
export DB_PORT="${DB_PORT:-5432}"
export DB_NAME="${DB_NAME:-ecommerce}"
export DB_USER="${DB_USER:-pipeline_reader}"
# DB_PASSWORD must be set externally — not stored here
export S3_BUCKET="${S3_BUCKET:-my-company-data-dev}"
export S3_PREFIX="${S3_PREFIX:-pipeline/orders}"
export MIN_EXPECTED_ROWS="${MIN_EXPECTED_ROWS:-100}"
export PYTHON="${PYTHON:-python3}"
export DATE="${DATE:-$(date +%Y-%m-%d)}"
export LOG_LEVEL="${LOG_LEVEL:-INFO}"
The ${VAR:-default} pattern is idiomatic shell parameterization: use the variable if set, otherwise use the default. This lets you override any setting at invocation time:
make DATE=2024-01-15 PIPELINE_ENV=staging S3_BUCKET=my-company-data-staging
This is the same config-driven approach described in parameterizing data pipelines for multiple environments — the principle holds whether you're using Airflow variables, Python config files, or shell environment variables.
Tip
Keep your config/env.sh in version control, but add a .env.local file (gitignored) for developer-specific overrides. At the top of env.sh, add [[ -f .env.local ]] && source .env.local. This lets individual developers override settings without polluting the repo.
The set -euo pipefail we configured earlier handles most errors automatically. But data pipelines need more than "stop on error" — they need to know what failed, why, and optionally clean up before stopping.
Create a scripts/lib/common.sh that all scripts source:
#!/usr/bin/env bash
# scripts/lib/common.sh — source this, don't run it
# ANSI colors for log levels
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
SCRIPT_NAME=$(basename "${BASH_SOURCE[1]}" .sh)
LOG_LEVEL="${LOG_LEVEL:-INFO}"
log_info() { echo -e "${GREEN}[INFO]${NC} [$(date '+%Y-%m-%d %H:%M:%S')] [$SCRIPT_NAME] $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} [$(date '+%Y-%m-%d %H:%M:%S')] [$SCRIPT_NAME] $*" >&2; }
log_error() { echo -e "${RED}[ERROR]${NC} [$(date '+%Y-%m-%d %H:%M:%S')] [$SCRIPT_NAME] $*" >&2; }
# Cleanup handler — register files to delete on failure
CLEANUP_FILES=()
register_cleanup() { CLEANUP_FILES+=("$@"); }
on_error() {
local exit_code=$?
local line_number=$1
log_error "Pipeline failed at line $line_number with exit code $exit_code"
if [[ ${#CLEANUP_FILES[@]} -gt 0 ]]; then
log_warn "Cleaning up temporary files..."
rm -f "${CLEANUP_FILES[@]}"
fi
# Emit a structured JSON event for monitoring systems
cat >&2 <<EOF
{
"event": "pipeline_step_failure",
"script": "$SCRIPT_NAME",
"exit_code": $exit_code,
"line": $line_number,
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
}
trap 'on_error $LINENO' ERR
Now your scripts look like this:
#!/usr/bin/env bash
set -euo pipefail
source "$(dirname "$0")/lib/common.sh"
# ... parse args ...
TEMP_OUTPUT="${OUTPUT}.tmp"
register_cleanup "$TEMP_OUTPUT" # Will be deleted if script fails
log_info "Starting extraction for date: $DATE"
psql ... > "$TEMP_OUTPUT"
log_info "Extraction complete, moving to final location"
mv "$TEMP_OUTPUT" "$OUTPUT"
This pattern — borrowed from data pipeline error handling and recovery strategies — ensures that a failed step never leaves behind partial output that could confuse downstream steps.
For steps that call external services (databases, APIs, S3), you want retry logic. Here's a reusable retry wrapper:
# scripts/lib/retry.sh
retry() {
local max_attempts="${1}"; shift
local delay="${1}"; shift
local attempt=1
while true; do
if "$@"; then
return 0
fi
if [[ $attempt -ge $max_attempts ]]; then
log_error "Command failed after $max_attempts attempts: $*"
return 1
fi
log_warn "Attempt $attempt/$max_attempts failed, retrying in ${delay}s..."
sleep "$delay"
delay=$((delay * 2)) # Exponential backoff
attempt=$((attempt + 1))
done
}
Call it like this in your extract script:
retry 3 5 psql \
--host="${DB_HOST}" \
--command "SELECT ..." > "$TEMP_OUTPUT"
This gives you three attempts with 5s → 10s → 20s exponential backoff — the same pattern used in production API integrations and described in pipeline retry logic and exponential backoff.
Data quality validation isn't a nice-to-have — it's what prevents bad data from reaching downstream consumers. Here's a minimal scripts/validate.py that illustrates the pattern:
#!/usr/bin/env python3
"""
Validate enriched orders data and convert to Parquet.
Exits non-zero if validation fails — Make will catch this and stop.
"""
import argparse
import sys
import logging
import json
from datetime import datetime
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s"
)
logger = logging.getLogger("validate")
def load_rules(rules_path: str) -> dict:
import yaml
with open(rules_path) as f:
return yaml.safe_load(f)
def validate(df: pd.DataFrame, rules: dict) -> list[dict]:
failures = []
# Rule: no nulls in critical columns
for col in rules.get("not_null", []):
null_count = df[col].isnull().sum()
if null_count > 0:
failures.append({
"rule": "not_null",
"column": col,
"failed_rows": int(null_count),
"severity": "error"
})
# Rule: value must be in allowed set
for rule in rules.get("allowed_values", []):
col = rule["column"]
allowed = set(rule["values"])
invalid = df[~df[col].isin(allowed)][col].unique().tolist()
if invalid:
failures.append({
"rule": "allowed_values",
"column": col,
"invalid_values": invalid[:10], # Cap at 10 for log readability
"severity": rule.get("severity", "error")
})
# Rule: numeric range
for rule in rules.get("range_check", []):
col = rule["column"]
out_of_range = df[
(df[col] < rule.get("min", float("-inf"))) |
(df[col] > rule.get("max", float("inf")))
]
if len(out_of_range) > 0:
failures.append({
"rule": "range_check",
"column": col,
"failed_rows": len(out_of_range),
"severity": rule.get("severity", "warn")
})
return failures
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--rules", required=True)
args = parser.parse_args()
logger.info(f"Loading data from {args.input}")
df = pd.read_csv(args.input, parse_dates=["order_date", "created_at"])
logger.info(f"Loaded {len(df):,} rows, {len(df.columns)} columns")
rules = load_rules(args.rules)
failures = validate(df, rules)
errors = [f for f in failures if f["severity"] == "error"]
warnings = [f for f in failures if f["severity"] == "warn"]
for w in warnings:
logger.warning(f"Validation warning: {json.dumps(w)}")
if errors:
for e in errors:
logger.error(f"Validation failure: {json.dumps(e)}")
logger.error(f"Validation failed with {len(errors)} error(s). Aborting.")
sys.exit(1)
logger.info(f"Validation passed ({len(warnings)} warnings)")
# Write Parquet with explicit schema
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
table = pa.Table.from_pandas(df)
pq.write_table(
table,
str(output_path),
compression="snappy",
row_group_size=100_000
)
logger.info(f"Written to {args.output}")
if __name__ == "__main__":
main()
The critical design decision: when validation fails at the error level, the script exits with a non-zero code. Make sees this, marks the target as failed, and stops. The validated Parquet file is never created, which means Make will also refuse to run the load step. You get automatic propagation of failure through the dependency chain without writing any special "if error, stop" logic. This directly implements the data quality validation principle that quality gates must actually gate.
One of Make's killer features is that you can re-run from any point in the pipeline. If your enrichment step failed, you don't need to re-extract and re-clean:
# Resume from the enrichment step (Make will find that raw and cleaned files exist and are fresh)
make data/enriched/orders_2024-01-15.csv DATE=2024-01-15
# Or explicitly force a step to re-run even if its output exists
make --always-make data/cleaned/orders_2024-01-15.csv DATE=2024-01-15
# Or just delete the file for that step and re-run all
rm data/cleaned/orders_2024-01-15.csv
make all DATE=2024-01-15
For the cases where you want to backfill historical data, you can run Make in a loop:
#!/usr/bin/env bash
# scripts/backfill.sh
set -euo pipefail
START_DATE="${1:?Usage: backfill.sh START_DATE END_DATE}"
END_DATE="${2:?Usage: backfill.sh START_DATE END_DATE}"
CURRENT="$START_DATE"
FAILURES=()
while [[ "$CURRENT" != "$END_DATE" ]]; do
echo "=== Backfilling $CURRENT ==="
if make all DATE="$CURRENT" -j1; then
echo "✓ $CURRENT complete"
else
echo "✗ $CURRENT FAILED"
FAILURES+=("$CURRENT")
fi
CURRENT=$(date -d "$CURRENT + 1 day" +%Y-%m-%d)
done
if [[ ${#FAILURES[@]} -gt 0 ]]; then
echo "BACKFILL COMPLETE WITH FAILURES:"
printf ' - %s\n' "${FAILURES[@]}"
exit 1
fi
echo "Backfill complete: $START_DATE through $END_DATE"
Tip
When backfilling, run with -j1 (single job) unless you've specifically designed your pipeline to handle parallel execution. Parallel backfills can overwhelm your database, hit API rate limits, or create file naming collisions.
Your pipeline is useless without visibility into what happened. We've already set up per-step log files. Let's add a structured summary:
# Add to Makefile after the main targets
.PHONY: pipeline-summary
pipeline-summary:
@echo "=== Pipeline Run Summary ==="
@echo "Date: $(DATE)"
@echo "Environment: $(PIPELINE_ENV)"
@if [[ -f "$(VALIDATED_DIR)/orders_$(DATE).parquet" ]]; then \
echo "Status: SUCCESS"; \
ls -lh "$(VALIDATED_DIR)/orders_$(DATE).parquet"; \
else \
echo "Status: INCOMPLETE (final output not found)"; \
fi
@echo ""
@echo "Step outputs:"
@for f in \
"$(RAW_DIR)/orders_$(DATE).csv" \
"$(CLEANED_DIR)/orders_$(DATE).csv" \
"$(ENRICHED_DIR)/orders_$(DATE).csv" \
"$(VALIDATED_DIR)/orders_$(DATE).parquet"; do \
if [[ -f "$$f" ]]; then \
echo " ✓ $$f ($$(wc -l < $$f) lines, $$(du -sh $$f | cut -f1))"; \
else \
echo " ✗ $$f (missing)"; \
fi; \
done
.PHONY: notify-slack
notify-slack:
@if [[ -n "${SLACK_WEBHOOK_URL:-}" ]]; then \
curl -s -X POST "$(SLACK_WEBHOOK_URL)" \
-H 'Content-type: application/json' \
-d "{\"text\": \"Pipeline complete: orders $(DATE) in $(PIPELINE_ENV)\"}" \
> /dev/null; \
fi
For more sophisticated monitoring — structured log aggregation, alerting, pipeline-level SLAs — this Makefile approach integrates cleanly with external tools. Your logs are plain text files that any log shipper (Fluentd, Vector, CloudWatch Logs agent) can tail and forward. The logging, alerting, and observability principles apply just as much here as in Airflow — the difference is you're wiring things up yourself rather than getting them from the framework.
The final piece is execution scheduling. The simplest production-grade option is cron:
# Run the pipeline at 2:00 AM UTC every day
# crontab -e
0 2 * * * /bin/bash -c 'cd /opt/pipeline && source /opt/pipeline/.env && make all DATE=$(date +\%Y-\%m-\%d) >> logs/cron.log 2>&1'
A more robust version uses a wrapper script that handles the log directory setup and sends a notification on failure:
#!/usr/bin/env bash
# scripts/run_pipeline.sh — Called by cron
set -euo pipefail
PIPELINE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PIPELINE_DIR"
export DATE="${DATE:-$(date +%Y-%m-%d)}"
export PIPELINE_ENV="${PIPELINE_ENV:-production}"
# Source secrets from a credential store (not from a file in the repo)
eval "$(aws secretsmanager get-secret-value \
--secret-id pipeline/db-credentials \
--query SecretString \
--output text | python3 -c "
import json, sys
for k, v in json.load(sys.stdin).items():
print(f'export {k}={v}')
")"
echo "[$(date)] Starting pipeline for $DATE in $PIPELINE_ENV"
if make all DATE="$DATE"; then
make pipeline-summary DATE="$DATE"
make notify-slack DATE="$DATE"
echo "[$(date)] Pipeline SUCCESS"
else
EXIT_CODE=$?
echo "[$(date)] Pipeline FAILED with exit code $EXIT_CODE" >&2
# Alert on failure
curl -s -X POST "${SLACK_WEBHOOK_URL}" \
-H 'Content-type: application/json' \
-d "{\"text\": \"🚨 Pipeline FAILED for $DATE in $PIPELINE_ENV. Check logs at $PIPELINE_DIR/logs\"}"
exit $EXIT_CODE
fi
Warning
Never store database passwords or API keys in config/env.sh or anywhere in your git repository. The pattern above pulls credentials from AWS Secrets Manager at runtime. For more on this, see the full treatment in secrets management and credential rotation for data pipelines.
Build a three-step CSV transformation pipeline using this lesson's patterns. Here's the scenario: you have a directory of raw sales CSV files (one per region) that need to be concatenated, deduplicated, and aggregated.
Step 1: Create the raw data
mkdir -p data/raw/sales data/processed/merged data/processed/deduplicated data/processed/aggregated
# Create sample data
for region in north south east west; do
python3 -c "
import csv, random, sys
from datetime import date, timedelta
writer = csv.writer(sys.stdout)
writer.writerow(['transaction_id', 'product_sku', 'region', 'revenue', 'sale_date'])
for i in range(200):
day = date(2024, 1, 15) + timedelta(days=random.randint(-5, 5))
writer.writerow([
f'TXN-{random.randint(10000, 99999)}',
f'SKU-{random.choice([\"A1001\", \"B2002\", \"C3003\", \"A1001\"])}',
'$region',
round(random.uniform(10, 500), 2),
str(day)
])
" > "data/raw/sales/${region}.csv"
done
Step 2: Write the Makefile
Create a Makefile with these three targets using the patterns from this lesson:
data/processed/merged/all_sales.csv: concatenate all regional files (hint: use cat and awk to handle headers)data/processed/deduplicated/all_sales.csv: deduplicate on transaction_id (hint: use Python)data/processed/aggregated/by_sku.csv: aggregate revenue by SKU and date (hint: use Python with pandas groupby)Step 3: Add error handling
Add a minimum-row check after the merge step. If fewer than 500 rows were merged (from 4 regions × 200 rows, you'd expect ~800), fail with a clear error message.
Step 4: Test partial re-runs
Delete only the deduplicated file and run make data/processed/aggregated/by_sku.csv. Verify that only the deduplication and aggregation steps run — not the merge step.
"Nothing to be done for 'all'"
This means Make thinks everything is up to date. Either your output files already exist and are newer than their inputs, or you're using .PHONY targets that have already run. For debugging, run make --dry-run all to see what Make would do without executing it. Run make --debug=v all for verbose dependency resolution output.
A script fails but Make keeps going
Check whether you have .SHELLFLAGS := -eu -o pipefail -c set. Without -e, Make only checks the exit code of the last line in a recipe — multi-line recipes may have earlier failures that go undetected.
"Circular dependency" errors
This happens when target A depends on B, which depends on A. Draw your dependency graph on paper before writing the Makefile. Each target should represent a distinct output file, not an operation.
Tab vs. space indentation
If you get Makefile:12: *** missing separator. Stop., you have a space where a tab should be. Use cat -A Makefile | grep -n "^ " to find lines with space-only indentation.
Variables not expanding inside recipes
Makefile has two expansion contexts: Make-time (when the Makefile is parsed) and recipe-time (when the shell runs). Use $(MAKE_VAR) for Make variables and $$SHELL_VAR for shell variables inside recipes. Forgetting the double dollar sign is extremely common.
Long-running steps that partially write output
Always write to a temp file and rename atomically on success. We covered this in the extract script — apply the same pattern everywhere. If your script is killed mid-write, Make will see a partial output file with a recent timestamp and think the step succeeded.
Note
When running pipelines on EC2 or similar cloud VMs, cron jobs may not inherit the environment variables you've set in your shell session. Always source your environment file explicitly in your cron wrapper script, or use systemd timer units which give you finer control over the execution environment.
This approach works exceptionally well when:
You should consider scheduling and orchestrating with Airflow when:
The honest advice: start with Make and shell. When you feel the pain of what it can't do, you'll have a much clearer picture of what you actually need from a heavier tool. Many mature data teams run hybrid stacks where Airflow orchestrates major pipeline families and Make or shell scripts handle individual data processing steps within those families.
You've built a production-quality multi-step transformation pipeline using nothing but Make and shell scripts. Here's what you can now do:
set -euo pipefail, trap, and atomic file writesThe natural next step depends on what's limiting you. If you need better data quality enforcement, dig into data quality validation, testing, and monitoring. If your pipeline is reading from APIs or databases with complex connection logic, connecting to databases, flat files, and cloud storage will help you harden those integrations. And when you're ready to graduate to a full orchestration platform, the dependency-graph thinking you've built here will transfer directly — you'll understand exactly what Airflow is doing for you because you've done it yourself.
Data Pipeline Fundamentals