Please enable JavaScript to use CodeHS

Terminal & Bash — Tutorial 3

Pipes and Filters

One of the terminal's superpowers is chaining small programs together. Instead of writing one giant tool that does everything, Unix-style systems have many tiny tools that each do one job well. You connect them with pipes.

Input, output, and streams

Every command has three standard streams:

  • stdin — the input stream, what you type or what another command sends in.
  • stdout — the normal output stream, what the command prints.
  • stderr — the error stream, used for warnings and problems.

By default, stdin comes from the keyboard and stdout goes to the screen. A filter reads stdin, transforms it, and writes the result to stdout. That makes filters easy to chain.

Pipes

A pipe is written as a vertical bar: |. It takes the stdout of the command on the left and sends it to the stdin of the command on the right.

For example, this line prints the first five lines of a file that contain the word "apple":

Example pipe
grep apple fruit.txt | head -5

grep filters the lines, and head trims the result. You can keep adding pipes to build a pipeline that solves exactly your problem.

Common filters

These small tools show up in almost every pipeline:

  • cat file — print a file's contents.
  • grep word — keep only lines containing a word.
  • sort — sort lines alphabetically. sort -n sorts numerically.
  • head -10 — keep the first 10 lines.
  • tail -10 — keep the last 10 lines.
  • wc -l — count lines.

The key idea is that each command does one thing. Pipes let you combine them like LEGO blocks.

Saving output to a file

Sometimes you want to keep the result instead of printing it. The > symbol redirects stdout into a file. Using two angle brackets, >>, appends to the end of an existing file.

Redirect output
cat scores.txt | sort -n > ranked.txt

This reads the scores, sorts them numerically, and writes the sorted list to ranked.txt. The original file is unchanged.

Try the pipe lab

A file called data/grades.txt holds scores for a class. Each line looks like Name Score. Experiment with filters and pipes to answer questions like "Who has the highest score?" or "How many students passed 70?"

bash — ~/home

Check yourself

Build a one-line pipeline that lists all students who scored at least 80, sorted from highest to lowest. Hint: first filter, then sort with sort -n, and use tail to keep the highest ones.

There is no single right answer. A common solution is cat data/grades.txt | grep 8 | sort -n | tail -5.

Quick quiz

1. What does the | symbol do?

2. Which filter counts lines?

3. What does > do?

Keep learning

You can now chain commands and save their output. Next, learn how to write reusable scripts in Bash.

Tutorial 3 of the “Terminal & Bash” series.