Pipes & Redirection
16 min
> writes a command's output to a file, replacing whatever was there;
>> appends instead of replacing. A pipe (|) chains commands
together — the output of the command on the left becomes the input of the
command on the right, with no file ever touching disk in between. You can
chain more than two: cat f.txt | sort | head -n 5 sorts a file's lines
and prints the first five, entirely in memory.
grep ERROR access.log | wc -l
# 2
grep ERROR access.log | wc -l > error-count.txt
cat error-count.txt
# 2
Each stage only sees what the previous stage printed — sort never knows the data came from a file, and head never knows it came through a pipe instead of a file. That's what makes pipes composable: every command speaks the same plain-text interface.
A file `access.log` already exists with one status per line (some `OK`, some `ERROR`). Count how many lines contain `ERROR` and write JUST that number, on its own, to a file called `error-count.txt`.
In `grep ERROR access.log | wc -l > error-count.txt`, what does the pipe (`|`) do?
You can chain commands with pipes and redirect their final output to a file.