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
- Pipes (
|) send one command's output into the next:
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.
- Redirection:
> filewrites output to a file (replacing it);>> fileadds to the end;2> errors.txtsends error messages to a file;-
command > out.log 2>&1sends both output and errors to one file. -
Shell scripts put commands in a file to repeat them:
#!/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).
-
Good habits:
set -euo pipefailat the top; quote variables ("$BACKUP_DIR") so spaces don't break things; test on your lab first. -
Scheduling:
crontab -eruns scripts on a schedule;0 2 * * * /srv/crm/backup.shruns at 2 a.m. daily. (systemd timers are a modern alternative.) -
With AI: AI writes shell scripts well, and dangerous ones convincingly. Read every line, especially
rm,>and anything withsudo, and run it in your lab first.
🖱️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.
