Skip to content

Pipes: connect commands with |

Send one command’s output into another with the | pipe: count files with ls | wc -l, sort and trim lists with head. Practise pipes in your browser.

Lesson 12 of 166 minSkip to the terminal ↓

Linux commands are small, and each does one job well. The pipe, |, joins them: the output of the command on the left becomes the input of the command on the right.

ls photos | wc -l

ls photos prints one name per line. Instead of reaching the screen, those lines flow into wc -l (word count, counting lines), which prints a single number: how many files there are.

Building a pipeline

Pipelines are built one step at a time. Run the first command, look at what it prints, then add the next:

cat names.txt
sort names.txt
sort names.txt | head -n 3

Commands that read their input and print a changed version are called filters. You already know some:

  • sort puts lines in order (-r reverses it, -n sorts by number),
  • head and tail keep the start or the end,
  • wc -l counts lines,
  • grep keeps matching lines (next lesson).

You can chain as many as you like: sort names.txt | tail -n 5 | sort -r.

A pipe passes output, not files. wc -l photos fails because photos is a directory; ls photos | wc -l counts what ls printed.

Your task

Use pipes for both: count how many files are in photos (with ls and wc -l), then show the first 3 names from names.txt in alphabetical order (with sort and head).

  • Count the photos: ls … | wc -l (not done yet)
  • The first 3 names, alphabetically (not done yet)

Lesson 12 of 16.

learner@sandbox: ~bash (practice)
Note: Practice shell for this lesson. Type a command and press Enter (help lists them all).