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.
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 -lls 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.txtsort names.txtsort names.txt | head -n 3Commands that read their input and print a changed version are called filters. You already know some:
sortputs lines in order (-rreverses it,-nsorts by number),headandtailkeep the start or the end,wc -lcounts lines,grepkeeps matching lines (next lesson).
You can chain as many as you like: sort names.txt | tail -n 5 | sort -r.
Tip:A pipe passes output, not files. wc -l photos fails because photos is a directory; ls photos | wc -l counts what ls printed.
Your turn
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).
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)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
|- Pipe: sends the output of one command into the next one
wc -l- Only the number of lines More on wc →
sort- Sort lines of text More on sort →
head- Print the first lines of files More on head →