Module 64: Linux Commands

Lesson 5 of 5 · 15–25 minutes

Pipes, redirection and scripts

🏠The everyday picture

An assembly line: one worker cuts, passes to the next who sews, who passes to the next who packs. Each does one simple job well; together they make the product.

📘What it really is

grep "error" /var/log/syslog | tail -n 20
cat access.log | cut -d' ' -f1 | sort | uniq -c | sort -rn | head

The second counts requests per IP address and shows the top ten.

#!/usr/bin/env bash
set -euo pipefail          # stop on errors, unset variables, failed pipes

BACKUP_DIR="/srv/backups"
STAMP=$(date +%Y-%m-%d_%H%M)
mkdir -p "$BACKUP_DIR"
cp /srv/crm/data/crm.db "$BACKUP_DIR/crm-$STAMP.db"
echo "Backup saved: crm-$STAMP.db"

Make it runnable (chmod +x backup.sh) and run it (./backup.sh).

🖱️Try it

Write backup.sh as above (adjusted to a file in your lab) and run it. Schedule it with cron to run every 5 minutes, check that backups appear, then remove the cron line. Write a one-line pipe that shows the 5 largest files in /var/log (sudo du -ah /var/log | sort -rh | head -n 5).

✅Quick check

What's the difference between > and >>?

Show the answer

> replaces the file's contents; >> adds to the end.

Why start scripts with set -euo pipefail?

Show the answer

So they stop at the first error instead of carrying on and doing damage.

← PreviousProcesses
ProLearners Assist